Skip to content

Instantly share code, notes, and snippets.

@npike
Created March 22, 2019 21:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npike/765d83299aeeb86f2c0931fc4f221ec9 to your computer and use it in GitHub Desktop.
Save npike/765d83299aeeb86f2c0931fc4f221ec9 to your computer and use it in GitHub Desktop.
zipMergeLiveData
fun <A, B, R> zipMergeLiveData(a: LiveData<A>, b: LiveData<B>, zipper: (A, B) -> R): LiveData<R> {
return MediatorLiveData<R>().apply {
var lastA: A? = null
var lastB: B? = null
fun update() {
val localLastA = lastA
val localLastB = lastB
if (localLastA != null && localLastB != null) {
val foo = zipper.invoke(localLastA, localLastB)
this.value = foo
}
}
addSource(a) {
lastA = it
update()
}
addSource(b) {
lastB = it
update()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment