Created
March 31, 2020 22:37
-
-
Save krage/9c9bf60546ddd447aacc789d26441834 to your computer and use it in GitHub Desktop.
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
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