Skip to content

Instantly share code, notes, and snippets.

@Sloy
Created February 6, 2018 11:08
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 Sloy/7a267237f7bc27a2057be744209c1c61 to your computer and use it in GitHub Desktop.
Save Sloy/7a267237f7bc27a2057be744209c1c61 to your computer and use it in GitHub Desktop.
Kotlin extensions for LiveData
package com.sloydev.macookbuk.infrastructure.extensions
import android.arch.lifecycle.*
fun <T, R> LiveData<T>.map(transformation: (T) -> R): LiveData<R> {
return Transformations.map(this, transformation)
}
fun <A, B, C> LiveData<A>.zipWith(other: LiveData<B>, zipFunc: (A, B) -> C): LiveData<C> {
return ZippedLiveData<A, B, C>(this, other, zipFunc)
}
/**
* Not sure why using the direct method doesn't work...
*/
fun <T> LiveData<T>.observe(owner: LifecycleOwner, f: (T?) -> Unit) {
this.observe(owner, object : Observer<T> {
override fun onChanged(t: T?) {
f(t)
}
})
}
fun <T> LiveData<T>.observeNonNull(owner: LifecycleOwner, f: (T) -> Unit) {
this.observe(owner, object : Observer<T> {
override fun onChanged(t: T?) {
t?.let(f)
}
})
}
class ZippedLiveData<A, B, C>(
private val ldA: LiveData<A>,
private val ldB: LiveData<B>,
private val zipFunc: (A, B) -> C
) : MediatorLiveData<C>() {
private var lastValueA: A? = null
private var lastValueB: B? = null
init {
addSource(ldA) {
lastValueA = it
emitZipped()
}
addSource(ldB) {
lastValueB = it
emitZipped()
}
}
private fun emitZipped() {
val valueA = lastValueA
val valueB = lastValueB
if (valueA != null && valueB != null) {
value = zipFunc(valueA, valueB)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment