Watch LiveData from ViewModel

I have a separate class in which I process data sampling (in particular, Firebase), and I usually return LiveData objects from it and update them asynchronously. Now I want the returned data to be stored in the ViewModel, but the problem is that in order to get the mentioned value, I need to watch the LiveData object returned from the data extraction class. The observation method required that the LifecycleOwner be the first parameter, but I obviously do not have this inside my ViewModel, and I know that I should not store the reference to the Activity / Fragment inside the ViewModel. What should I do?

+47
source share
4 answers

In this blog post from Google developer Jose Alkerreki, we recommend that you use the transform in this case (see "LiveData in repositories" paragraph).

+21
source

ViewModel documentation

However, ViewModel objects should never observe changes in the observed life cycles of objects, such as LiveData objects.

Another way is that the data implements RxJava and not LiveData, then the advantage is that they will take into account the life cycle.

In the Google example todo-mvvm-live-kotlin, it uses a callback without LiveData in the ViewModel.

, , Activity/Fragment. , callback RxJava ViewModel.

MediatorLiveData ( Transformations) ( ) ViewModel. , MediatorLiveData ( , Transformations), Activity/Fragment. , Activity/Fragment, ViewModel.

// ViewModel
fun start(id : Long) : LiveData<User>? {
    val liveData = MediatorLiveData<User>()
    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: ViewModels LiveData: Patterns + AntiPatterns, . , , LiveData (, , , Activity/Fragment).

+14

. MediatorLiveData

. MediatorLiveData

0

I think you can use applyForever, which does not require a lifecycle owner interface, and you can observe the results from a view model

0
source

Source: https://habr.com/ru/post/1689911/


All Articles