merge

fun <T : Any, S : Any> LiveData<out Collection<S>>.merge(mapFunction: (S) -> LiveData<out T?>): LiveData<out Collection<T>>

Transforms LiveData containing a list that holds other LiveData instances into LiveData that contains the values from those LiveData instances. The returned LiveData will be updated when the source LiveData changes as well as when the internal LiveData instances change.

When LiveData instance has not a value yet, the returned LiveData will also not have a value and the mapFunction and observes will not be invoked until a LiveData instance has a value. This is comparable to how other MediatorLiveData transformations behave.

For example:

// GIVEN
class Holder(val liveProperty: LiveData<Int>)
val sources = MutableLiveData<List<Holder>>(
listOf(
Holder(MutableLiveData(1)),
Holder(MutableLiveData(2))
)
)

// WHEN
val merged = sources.merge { it.liveProperty }

// THEN
// Observing merged.value yields listOf(1, 2)

// WHEN
sources.value[0].liveProperty.value = 0

// THEN
// Observing merged.value yields listOf(0, 2)

Parameters

T

The type of the list elements to merge.

S

The type of the source LiveData values.

mapFunction

A function that maps sources to T.