Skip to content

Instantly share code, notes, and snippets.

@pretorh
Last active August 10, 2019 21:04
Show Gist options
  • Save pretorh/404b7cb88d6f01228d3605abab8d890e to your computer and use it in GitHub Desktop.
Save pretorh/404b7cb88d6f01228d3605abab8d890e to your computer and use it in GitHub Desktop.
merge two live data sources into a single mediator live data, returning data when either of them changed (not chained)
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
fun <T1, T2> mergeLiveData(source1: LiveData<T1>, source2: LiveData<T2>): LiveData<Pair<T1, T2>> {
val result = MediatorLiveData<Pair<T1, T2>>()
var data1: T1? = null
var data2: T2? = null
fun postDataIfBothAvailable() {
val first = data1 ?: return
val second = data2 ?: return
result.postValue(Pair(first, second))
}
result.addSource(source1) { data1 = it ; postDataIfBothAvailable() }
result.addSource(source2) { data2 = it ; postDataIfBothAvailable() }
return result
}
@pretorh
Copy link
Author

pretorh commented Aug 10, 2019

observe 2 live data sources independently (not chained) and post when either changes

val liveData = MediatorLiveData<...>()
liveData.addSource(source1) { data1 ->
    liveData.addSource(source2) {
        // do something
    }
}

fails when the source1 is changed, since it re-adds source2

based on https://stackoverflow.com/a/52306675/1016377

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment