Last active
August 10, 2019 21:04
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
observe 2 live data sources independently (not chained) and post when either changes
fails when the
source1
is changed, since it re-addssource2
based on https://stackoverflow.com/a/52306675/1016377