MediatorLiveData

open class MediatorLiveData<T : Any!>
kotlin.Any
   ↳ androidx.lifecycle.MediatorLiveData

LiveData subclass which may observe other LiveData objects and react on OnChanged events from them.

This class correctly propagates its active/inactive states down to source LiveData objects.

Consider the following scenario: we have 2 instances of LiveData, let's name them liveData1 and liveData2, and we want to merge their emissions in one object: liveDataMerger. Then, liveData1 and liveData2 will become sources for the MediatorLiveData 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)); 

Let's consider that we only want 10 values emitted by liveData1, to be merged in the liveDataMerger. Then, after 10 values, we can stop listening to liveData1 and remove it as a source.

 liveDataMerger.addSource(liveData1, new Observer() { private int count = 1; @Override public void onChanged(@Nullable Integer s) { count++; liveDataMerger.setValue(s); if (count > 10) { liveDataMerger.removeSource(liveData1); } } }); 

Summary

Public constructors

Public methods
open Unit
addSource(source: LiveData<S>, onChanged: Observer<in S>)

Starts to listen the given source LiveData, onChanged observer will be called when source value was changed.

open Unit
removeSource(toRemote: LiveData<S>)

Stops to listen the given LiveData.

Protected methods
open Unit

open Unit

Public constructors

<init>

MediatorLiveData()

Public methods

addSource

open fun <S : Any!> addSource(source: LiveData<S>, onChanged: Observer<in S>): Unit

Starts to listen the given source LiveData, onChanged observer will be called when source value was changed.

onChanged callback will be called only when this MediatorLiveData is active.

If the given LiveData is already added as a source but with a different Observer, IllegalArgumentException will be thrown.

Parameters
source LiveData<S>: the LiveData to listen to
onChanged LiveData<S>: The observer that will receive the events
<S> LiveData<S>: The type of data hold by source LiveData

removeSource

open fun <S : Any!> removeSource(toRemote: LiveData<S>): Unit

Stops to listen the given LiveData.

Parameters
toRemote LiveData<S>: LiveData to stop to listen
<S> LiveData<S>: the type of data hold by source LiveData

Protected methods

onInactive

protected open fun onInactive(): Unit

onActive

protected open fun onActive(): Unit