I have a separate class in which I handle data fetching (specifically Firebase) and I usually return LiveData objects from it and update them asynchronously. Now I want to have
However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects.
In this Github issue, he describes that the situations that be applied the above rule are that observed lifecycle-aware observables are hosted by another lifecycle scope.
There is no problem that observes LiveData
in ViewModel
contains observed LiveData
.
class MyViewModel : ViewModel() {
private val myLiveData = MutableLiveData(1)
init {
viewModelScope.launch {
myLiveData.asFlow().collect {
// Do Something
}
}
}
}
class MyViewModel : ViewModel() {
private val myFlow = MutableStateFlow(1)
private val myLiveData = myFlow.asLiveData(viewModelScope.coroutineContext)
}
The asFlow
makes a flow that makes LiveData
activate at starting collect
. I think the solution with MediatorLiveData
or Transformations
and attaching a dummy observer doesn't have differences using the Flow
except for emitting value from LiveData
is always observed in the ViewModel
instance.