Good practice to implement viewmodel - android

Does anyone know good practice to implement viewmodel logic? Event based or action based?
class EventBasedVM : ViewModel() {
fun onResume() {
fetchInformation1()
fetchInformation2()
}
}
class ActionBasedVM : ViewModel() {
fun fetchInformation1() {
}
fun fetchInformation2() {
}
}

Although both approaches you mentioned make sense for specific use cases, I would add another one to the list:
class InitialisationBasedVM : ViewModel() {
val informationLiveData = MutableLiveData<String>()
init {
fetchInformation()
}
private fun fetchInformation() {
// call you async code and eventually post the value to the observers
informationLiveData.postValue("whatever")
}
}
The approach of fetching data in the ViewModel constructor make sure data are not fetched again in case of configuration changes. You could also make the fetchInformation() method public and invoke from the View upon certain actions that require reloading the data (i.e pull to refresh).

Related

How to prevent data duplication caused by LiveData observation in Fragment?

I'm subscribed to an observable in my Fragment, the observable listens for some user input from three different sources.
The main issue is that once I navigate to another Fragment and return to the one with the subscription, the data is duplicated as the observable is handled twice.
What is the correct way to handle a situation like this?
I've migrated my application to a Single-Activity and before it, the subscription was made in the activity without any problem.
Here is my Fragment code:
#AndroidEntryPoint
class ProductsFragment : Fragment() {
#Inject
lateinit var sharedPreferences: SharedPreferences
private var _binding: FragmentProductsBinding? = null
private val binding get() = _binding!!
private val viewModel: ProductsViewModel by viewModels()
private val scanner: CodeReaderViewModel by activityViewModels()
private fun observeBarcode() {
scanner.barcode.observe(viewLifecycleOwner) { barcode ->
if (barcode.isNotEmpty()) {
if (binding.searchView.isIconified) {
addProduct(barcode) // here if the fragment is resumed from a backstack the data is duplicated.
}
if (!binding.searchView.isIconified) {
binding.searchView.setQuery(barcode, true)
}
}
}
}
private fun addProduct(barcode: String) {
if (barcode.isEmpty()) {
return
}
viewModel.insert(barcode)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.start(args.documentId)
if (args.documentType == "Etichette") {
binding.cvLabels.visibility = View.VISIBLE
}
initUI()
observe()
}
private fun observe() {
observeBarcode()
observeProducts()
observeLoading()
observeLast()
}
}
Unfortunately, LiveData is a terribly bad idea (the way it was designed), Google insisted till they kinda phased it out (but not really since it's still there) that "it's just a value holder"...
Anyway... not to rant too much, the solution you have to use can be:
Use The "SingleLiveEvent" (method is officially "deprecated now" but... you can read more about it here).
Follow the "official guidelines" and use a Flow instead, as described in the official guideline for handling UI Events.
Update: Using StateFlow
The way to collect the flow is, for e.g. in a Fragment:
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) { // or RESUMED
viewModel.yourFlow.collectLatest { ... } // or collect { ... }
}
}
For that in your ViewModel you'd expose something like:
Warning: Pseudo-Code
// Imagine your state is represented in this sealed class
sealed class State {
object Idle: State
object Loading: State
data class Success(val name: String): State
data class Failure(val reason: String): State
}
// You need an initial state
private val _yourFlow = MutableStateFlow(State.Idle)
val yourFlow: StateFlow<State> = _yourFlow
Then you can emit using
_yourFlow.emit(State.Loading)
Every time you call
scanner.barcode.observe(viewLifecycleOwner){
}
You are creating a new anonymous observer. So every new call to observe will add another observer that will get onChanged callbacks. You could move this observer out to be a property. With this solution observe won't register new observers.
Try
class property
val observer = Observer<String> { onChanged() }
inside your method
scanner.barcode.observe(viewLifecycleOwner, observer)
Alternatively you could keep your observe code as is but move it to a Fragment's callback that only gets called once fex. onCreate(). onCreate gets called only once per fragment instance whereas onViewCreated gets called every time the fragment's view is created.

Android should you really use by Lazy in ViewModel as per Docs?

This Android doc shows following code:
class MyViewModel : ViewModel() {
private val users: MutableLiveData<List<User>> by lazy {
MutableLiveData<List<User>>().also {
loadUsers()
}
}
fun getUsers(): LiveData<List<User>> {
return users
}
private fun loadUsers() {
// Do an asynchronous operation to fetch users.
}
}
and I'm wondering if it is really correct to use by lazy or really needed since I can not encounter any projects using this. If you do use it and you for example do following:
private fun loadUsers() {
// Do an asynchronous operation to fetch users.
users.value = ...
}
the code access "users" again and since it is not initialized yet loadUsers() is called again! Considering you observe users in an activity or fragment for example.

ViewModel with Asynchronous Data Load and SavedStateHandle

I'm new to ViewModel and am trying to figure out what the best practices are for using SavedStateHandle in tandem with asynchronously loading data from an API.
My use case is that my ViewModel data should be loaded in once from the API, and after that I want the SavedStateHandle to save that data so if I come back to the fragment it doesn't perform that API call again. I only want that data refreshed from the API on a pull down to refresh mechanism in the UI, otherwise it should use the SavedStateHandle data.
I've found plenty of examples using one or the other (asynchronous data load or SavedStateHandle but not both.
Here is my initial code that does not use SavedStateHandle
class FilmsViewModel(private val savedStateHandle: SavedStateHandle): ViewModel() {
private val filmsLiveData : MutableLiveData<List<Film>?> by lazy {
MutableLiveData<List<Film>?>().also {
loadFilms()
}
}
fun getFilms(): LiveData<List<Film>?> {
return filmsLiveData
}
fun loadFilms() {
Log.d("FilmsViewModel", "loadFilms")
StarWarsApiService.getFilms(object: FilmsCallback {
override fun success(films: List<Film>?) {
filmsLiveData.value = films
}
}, object: ErrorCallback {
override fun error(error: ApiError) {
// TODO
}
})
}
}
Any ideas?
By default, the way Google intended (and which DOES try to re-fetch in onStart) you would make StarWarsApiService.getFilms be suspend fun instead of callback-based, then you can do
class FilmsViewModel(private val savedStateHandle: SavedStateHandle): ViewModel() {
val filmsLiveData = liveData {
emit(loadFilms())
}
}
But what you're looking for is a regular viewModelScope.launch { that saves the retrieved data in a MutableLiveData, OR into local storage (Room) that would expose a LiveData<List<T>> which would be observed by the Fragment.
SavedStateHandle isn't for data, it is for state.

How to observe ViewModel that makes a request for a call back

I am trying to make a request to a library that gives me a call back.
Manager.getInstance().request(new CallBack())
I want to put this in a ViewModel so that I can observe it from the Activity.
class RequestViewModel : ViewModel, CallBack {
fun request() {
Manager.getInstance().request(this)
}
override fun onFinished(result : List<String>?) {
}
override fun onFailed() {
}
}
How can I make it so that I can observe when this has finished? I know I could make my Activity implement this CallBack, but I don't want to couple Activity to this.
Ideally this would be a LiveData or Observable.
If I understand the question correctly, you can submit the data acquired in onFinished method to the LiveData instance that should be observed by a view component, e.g.
class RequestViewModel : ViewModel, CallBack {
private val _liveData = MutableLiveData<SomeResult<List<String>>>
val liveData: LiveData<SomeResult<List<String>>> get() = _liveData
fun request() {
Manager.getInstance().request(this)
}
override fun onFinished(result : List<String>?) {
if (result != null) {
_liveData.postValue(SomeResult.success(result))
} else {
_liveData.postValue(SomeResult.failure())
}
}
override fun onFailed() {
_liveData.postValue(SomeResult.failure())
}
}
And somewhere in your object that corresponds to a view component:
viewModel.liveData.observe(lifecycleOwner, Observer<List<String>> {
handleResponse(it)
})
whereas lifecycleOwner typically is your AppCompatActivity or android.support.v4.Fragment inheritor.
I would advise you to decouple requesting from ViewModel and create a class called Repository to handle all the requests. In this class you could have a MutableLiveData object which can be observed and whenever new requested data is retrieved, use mutableLiveData.postValue(retrievedData) for MutableLiveData which notifies the observes about the new changes.
To read more about repository, you can follow these links:
Google's Guide to App Architecture
Codelab tutorial with Repository pattern

Clean Architecture: ViewModel with multiple UseCases on Android

This is more of an Architecture question than a bug fixing one.
Let's assume this app lets users mark a Bus and/or Bus Stations as a favourite. My question is, should I have a ViewModel with both UseCases or should I build a UseCase that encapsulates the current logic?
Also for the question part, I'm not entirely sure the way I should expose the combined data to the UI layer (see favouritesExposedLiveData)
Thanks in advance any feedback is welcome, here's my ViewModel you can assume each UseCase is passing the correct data from the data source(s).
open class FavouritesViewModel #Inject internal constructor(
private val getFavouriteStationsUseCase: GetFavouriteStationsUseCase,
private val getFavouriteBusesUseCase: GetFavouriteBusesUseCase,
private val favouriteMapper: FavouriteMapper,
private val busMapper: BusMapper,
private val stationMapper: StationMapper) : ViewModel() {
private val favouriteBusesLiveData: MutableLiveData<Resource<List<BusView>>> = MutableLiveData()
private val favouriteStationsLiveData: MutableLiveData<Resource<List<StationView>>> = MutableLiveData()
private lateinit var favouritesMediatorLiveData: MediatorLiveData<List<FavouriteView>>
private lateinit var favouritesExposedLiveData: LiveData<Resource<List<FavouriteView>>>
init {
fetchFavourites()
}
override fun onCleared() {
getFavouriteStationsUseCase.dispose()
getFavouriteBusesUseCase.dispose()
super.onCleared()
}
fun getFavourites(): LiveData<Resource<List<FavouriteView>>> {
return favouritesExposedLiveData
}
private fun fetchFavourites() {
favouritesMediatorLiveData.addSource(favouriteStationsLiveData, { favouriteStationListResource ->
if (favouriteStationListResource?.status == ResourceState.SUCCESS) {
favouriteStationListResource.data?.map {
favouriteMapper.mapFromView(it)
}
}
})
favouritesMediatorLiveData.addSource(favouriteBusesLiveData, { favouriteBusesListResource ->
if (favouriteBusesListResource?.status == ResourceState.SUCCESS) {
favouriteBusesListResource.data?.map {
favouriteMapper.mapFromView(it)
}
}
})
getFavouriteStationsUseCase.execute(FavouriteStationsSubscriber())
getFavouriteBusesUseCase.execute(FavouriteBusesSubscriber())
}
inner class FavouriteStationsSubscriber : DisposableSubscriber<List<Station>>() {
override fun onComplete() {}
override fun onNext(t: List<Station>) {
favouriteStationsLiveData.postValue(Resource(ResourceState.SUCCESS, t.map { stationMapper.mapToView(it) }, null))
}
override fun onError(exception: Throwable) {
favouriteStationsLiveData.postValue(Resource(ResourceState.ERROR, null, exception.message))
}
}
inner class FavouriteBusesSubscriber : DisposableSubscriber<List<Bus>>() {
override fun onComplete() {}
override fun onNext(t: List<Bus>) {
favouriteBusesLiveData.postValue(Resource(ResourceState.SUCCESS, t.map { busMapper.mapToView(it) }, null))
}
override fun onError(exception: Throwable) {
favouriteBusesLiveData.postValue(Resource(ResourceState.ERROR, null, exception.message))
}
}
}
Note: Currently the MediatorLiveData (favouritesMediatorLiveData)is not binding the data back to the favouritesExposedLiveData since at this time, I'm not sure this is the correct way to go ;).
Ideally a ViewModel would only have the view state for its view. By using the MediatorLiveData you could aggregate all sources of state into one that represents the view state over time.
What you can have is a data class that represents your ViewState that you construct on your view model and is your exposed LiveData
data class FavouritesViewState(val favoriteStations: List<Station>, val favoritBuses: List<Bus>)
However you know depend on the ViewModel to construct the final ViewState which kinda breaks the single responsibility principle and also makes you dependent of an Android framework.
I would approach it using a composite UseCase that had both station and bus use cases and returns the composed data that you can then easily expose from the ViewModel.
The whole point of a ViewModel is that it is a model of what the view is using. It should be as close to that as possible.. Unless you are presenting stations and buses in the same view list (seems ugly), otherwise, they are separate views, and should get separate models.

Categories

Resources