Skip to content

Instantly share code, notes, and snippets.

@edenman
Created November 20, 2017 23:44
Show Gist options
  • Save edenman/0be7d32486b50c9f6141e6eb6ac59283 to your computer and use it in GitHub Desktop.
Save edenman/0be7d32486b50c9f6141e6eb6ac59283 to your computer and use it in GitHub Desktop.
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