Observing LiveData from ViewModel

后端 未结 6 2027
-上瘾入骨i
-上瘾入骨i 2021-01-30 05:07

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

6条回答
  •  醉话见心
    2021-01-30 05:31

    Use Flow

    The guideline in docs is misunderstood

    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.

    Use Flow

    class MyViewModel : ViewModel() {
        private val myLiveData = MutableLiveData(1)
    
        init {
            viewModelScope.launch {
                myLiveData.asFlow().collect {
                    // Do Something
                }
            }
        }
    }
    

    Use StateFlow

    class MyViewModel : ViewModel() {
        private val myFlow = MutableStateFlow(1)
        private val myLiveData = myFlow.asLiveData(viewModelScope.coroutineContext)
    }
    

    PS

    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.

提交回复
热议问题