Observing LiveData from ViewModel

后端 未结 6 2077
-上瘾入骨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条回答
  •  萌比男神i
    2021-01-30 05:20

    In ViewModel documentation

    However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects.

    Another way is for the data to implement RxJava rather than LiveData, then it won't have the benefit of being lifecycle-aware.

    In google sample of todo-mvvm-live-kotlin, it uses a callback without LiveData in ViewModel.

    I am guessing if you want to comply with the whole idea of being lifecycle-ware, we need to move observation code in Activity/Fragment. Else, we can use callback or RxJava in ViewModel.

    Another compromise is implement MediatorLiveData (or Transformations) and observe (put your logic here) in ViewModel. Notice MediatorLiveData observer won't trigger (same as Transformations) unless it's observed in Activity/Fragment. What we do is we put a blank observe in Activity/Fragment, where the real work is actually done in ViewModel.

    // ViewModel
    fun start(id : Long) : LiveData? {
        val liveData = MediatorLiveData()
        liveData.addSource(dataSource.getById(id), Observer {
            if (it != null) {
                // put your logic here
            }
        })
    }
    
    // Activity/Fragment
    viewModel.start(id)?.observe(this, Observer {
        // blank observe here
    })
    

    PS: I read ViewModels and LiveData: Patterns + AntiPatterns which suggested that Transformations. I don't think it work unless the LiveData is observed (which probably require it to be done at Activity/Fragment).

提交回复
热议问题