Skip to content

Instantly share code, notes, and snippets.

@edenman

edenman/RelayPair.kt

Created Nov 20, 2017
Embed
What would you like to do?
A helper class that exposes observables for two different types, as well as a single observable for both
class RelayPair<A, B> {
private val relayA = BehaviorRelay.create(null as A?)
private val relayB = BehaviorRelay.create(null as B?)
private val relayBoth = BehaviorRelay.create(Both<A, B>(null, null))
data class Both<out A, out B>(val a: A?, val b: B?)
fun publishA(value: A?) {
relayA.call(value)
relayBoth.call(relayBoth.value.copy(a = value))
}
fun publishB(value: B?) {
relayB.call(value)
relayBoth.call(relayBoth.value.copy(b = value))
}
fun publishBoth(a: A?, b: B?) {
relayA.call(a)
relayB.call(b)
relayBoth.call(Both(a, b))
}
fun observeA(): Observable<A?> = relayA
fun getA(): A? = relayA.value
fun observeB(): Observable<B?> = relayB
fun getB(): B? = relayB.value
fun observeBoth(): Observable<Both<A, B>> = relayBoth
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.