Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can LiveData in ViewModel observe the Livedata in Repository using Transformations?

I am using an AsyncTask in my repository which is used to set the LiveData in the repository. How do I observe this LiveData from my ViewModel using Transformations?

like image 603
Yadynesh Desai Avatar asked Dec 26 '17 06:12

Yadynesh Desai


People also ask

How do you observe LiveData in ViewModel?

Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.

How do you observe LiveData in repository?

Main + viewModelJob) private val _user = MutableLiveData<User>() val user: LiveData<User> get() = _user val email = MutableLiveData<String>() val password = MutableLiveData<String>() [...] fun onRegister() { val userEmail = email. value. toString() val userPassword = password. value.

What are the transformation functions available in LiveData package?

This class provides three static methods: map , switchMap and distinctUntilChanged which will be explained below.

What is LiveData transformation?

LiveData is an observable data holder class. We can observe the data inside it and whenever the data change, observer will be notified and handle the data change. Unlike the other observable data holder, LiveData is lifecycle aware meaning that it's only observable to observer that was inside an active lifecycle state.


1 Answers

You can ignore my other answer. The solution is using MediatorLiveData<> in your view model. You add the LiveData from the repository as a data source to the MediatorLiveData<> and call setValue or postValue (depends on if it is in the UI tread or not) in the observer onChanged callback.

Like so

    currentTransaction.addSource(application.getFinanceRepository().getTransaction(id),
            new Observer<Transaction>() {
        @Override
        public void onChanged(@Nullable Transaction transaction) {
            //Updates the MediatorLiveData<> that you activity is observing
            currentTransaction.setValue(transaction);
        }
    });
like image 69
SSMI Avatar answered Sep 18 '22 12:09

SSMI