What is difference between MediatorLiveData and MutableLiveData in MVVM

Lalit Kushwah picture Lalit Kushwah · Oct 25, 2017 · Viewed 23.3k times · Source

I have searched a lot but not found the crystal clear answer for the questions:

  1. What is the difference between MediatorLiveData and MutableLiveData?

  2. What are the suitable condition to use either of them.

Answer

Asad picture Asad · Feb 16, 2018

At first we need to know what is the relation between MutableLivedata and MediatorLivedata to understand the difference between them.

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

Now it is clear that MediatorLiveData is a subclass of MutableLiveData therefore MediatorLiveData can access each and every property of MutableLiveData as well as LiveData.

Question no. 1 is answered partially and rest of the answer will be discussed at the end of Question no. 2's answer.

After researching on some sample projects as well as android developer's official site I found that MutableLiveData should be used only for notifying your UI when observing any data.

For example, you want to display two SeekBars on two different fragments(Fragment1 and Fragment2) and you also want them to be synced when operating from Fragment1.

Another scenario is that we have 2 instances of LiveData, let's name them liveData1 and liveData2, and we want to merge their emissions in one object: liveDataMerger (which is a MediatorLiveData object). Then, liveData1 and liveData2 will become sources for the liveDataMerger and every time onChanged callback is called for either of them, we set a new value in liveDataMerger.

LiveData liveData1 = ...;
LiveData liveData2 = ...;

MediatorLiveData liveDataMerger = new MediatorLiveData<>();
liveDataMerger.addSource(liveData1, value ->liveDataMerger.setValue(value));
liveDataMerger.addSource(liveData2, value -> liveDataMerger.setValue(value));

In this case you cannot use MutableLiveData but on the other hand if you want to compare data into the first example (where MutableLiveData has been used) then you cannot because you will be unable to use the addSource property (as per class hierarchy).