Created
February 6, 2018 11:08
-
-
Save Sloy/7a267237f7bc27a2057be744209c1c61 to your computer and use it in GitHub Desktop.
Kotlin extensions for LiveData
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
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