androidkotlinandroid-livedataswitchmapmediatorlivedata

Which is a better way to combine multiple LiveData(s): using MediatorLiveData or switchMap?


Which approach is more recommended to combine multiple LiveData(s): using MediatorLiveData or switchMap?

// MediatorLiveData approach
fun <A, B, C> combine(
    liveData1: LiveData<A>,
    liveData2: LiveData<B>,
    onChanged: (A?, B?) -> C
): MediatorLiveData<C> {
    return MediatorLiveData<C>().apply {
        addSource(liveData1) {
            value = onChanged(liveData1.value, liveData2.value)
        }
        addSource(liveData2) {
            value = onChanged(liveData1.value, liveData2.value)
        }
    }
}

// switchMap approach
fun <A, B, C> combine(
    liveData1: LiveData<A>,
    liveData2: LiveData<B>,
    onChanged: (A, B) -> C
): LiveData<C> {
    return liveData1.switchMap { a ->
        liveData2.map { b ->
            onChanged(a, b)
        }
    }
}

The MediatorLiveData approach may be more common but the switchMap approach looks simpler. Both approaches seem to serve the same purpose in many cases.


Solution

  • You should be using MediatorLiveData directly.

    All Transformations. are actually MediatorLiveDatas - switchMap is just a mediator that dynamically swaps source depending on return value of provided switchMapFunction.

    Second approach just generates useless overhead - you allocate switchMap MediatorLiveData that keeps creating and swapping in new map MediatorLiveData objects whenever liveData1 changes.