Necessity of ViewModel and Difference Between MutableLiveData and MediatorLiveData

Md. Asaduzzaman Noor
TeachMind
Published in
2 min readMay 6, 2018

ViewModel is to help for saving(until onDestroy() is called) UI data and to communicate(realtime) between fragments placed at the same screens.

Note: ViewModel’s only responsibility is to manage the data for the UI. It should never access your view hierarchy or hold a reference back to the Activity or the Fragment.

Let’s see a short example where ViewModel has been used to modify the value of a number and also the value will not be reinitialised even if the device orientation changes.

After seeing this example code, you would like to ask one simple question that what is “MutableLiveData” and why should I use that instead of a simple LiveData object.

MutableLiveData is a subclass of LiveData which is used for some of it’s properties (setValue/postValue) and using these properties we can easily notify the ui when onChange() is called. Only using LiveData object we can’t do this. So, we have to convert the target object to MutableLiveData/MediatorLiveData for notifying on each time of changing data.

You may visit the whole project with viewModel examples from below repo..

Now another term comes up that is “MediatorLiveData”. It is very important to know about the difference and relation between MutableLiveData and MediatorLiveData.

java.lang.Objectandroid.arch.lifecycle.LiveData<T>android.arch.lifecycle.MutableLiveData<T>         ↳android.arch.lifecycle.MediatorLiveData<T>

The above relation is taken from Android Developer Site and I hope that you are now understanding the subclass hierarchy.

Now the question is when should I use MutableLiveData and when MediatorLiveData?

The answer is, lets say your need is only to update any LiveData object and also notify that object whenever the data value is changed as per my given example above then MutableLiveData is enough to serve that purpose.

If the case is like you have to compare two LiveData objects and you want to generate another new object from the emissions of their comparison then MediatorLiveData will be perfect to serve that purpose. Moreover, as we know that the MediatorLiveData is a subclass of MutableLiveData, we can still use each and every property of MutableLiveData. If you want to know more about this topic then you may visit one of my stackoverflow answer.

Another usage of ViewModel is to communicate between fragments. More specifically, if you have two fragments on the same screen and you want to update ui data concurrently to see realtime effect then ViewModel will do that for you with a very little amount of code.

I hope your understanding will be more clearer after visiting below code snippet.

If you have any question please let me know.

--

--

Md. Asaduzzaman Noor
TeachMind

Android App Developer using Kotlin, Java and Android Studio