Skip to content

Instantly share code, notes, and snippets.

@krage
Created March 31, 2020 22:37
Show Gist options
  • Save krage/9c9bf60546ddd447aacc789d26441834 to your computer and use it in GitHub Desktop.
Save krage/9c9bf60546ddd447aacc789d26441834 to your computer and use it in GitHub Desktop.
fun <A : Any, B : Any> LiveData<A>.pairLatest(b: LiveData<B>): LiveData<Pair<A, B>> =
object : MediatorLiveData<Pair<A, B>>() {
private var aReceived = false
private var lastA: A? = null
private var bReceived = false
private var lastB: B? = null
init {
addSource(this@pairLatest) {
aReceived = true
lastA = it
if (aReceived && bReceived) value = Pair(lastA!!, lastB!!)
}
addSource(b) {
bReceived = true
lastB = it
if (aReceived && bReceived) value = Pair(lastA!!, lastB!!)
}
}
}
fun <A, B> LiveData<A>.pairLatestNullable(b: LiveData<B>): LiveData<Pair<A?, B?>> =
object : MediatorLiveData<Pair<A?, B?>>() {
private var aReceived = false
private var lastA: A? = null
private var bReceived = false
private var lastB: B? = null
init {
addSource(this@pairLatestNullable) {
aReceived = true
lastA = it
if (aReceived && bReceived) value = Pair(lastA, lastB)
}
addSource(b) {
bReceived = true
lastB = it
if (aReceived && bReceived) value = Pair(lastA, lastB)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment