Skip to content

Instantly share code, notes, and snippets.

@mrahimygk
Forked from guness/CombinedLiveData.java
Created July 18, 2019 07:06
Show Gist options
  • Save mrahimygk/d5723f60d14be2c2a5004fde79bd54a6 to your computer and use it in GitHub Desktop.
Save mrahimygk/d5723f60d14be2c2a5004fde79bd54a6 to your computer and use it in GitHub Desktop.
LiveData merger that takes two live data inputs and a merger function. Merges two results using merger function, and returning result allowing null inputs and outputs. Input and out types are parametric. However only supports two live data inputs for now.
class CombinedLiveData<T, K, S>(source1: LiveData<T>, source2: LiveData<K>, private val combine: (data1: T?, data2: K?) -> S) : MediatorLiveData<S>() {
private var data1: T? = null
private var data2: K? = null
init {
super.addSource(source1) {
data1 = it
value = combine(data1, data2)
}
super.addSource(source2) {
data2 = it
value = combine(data1, data2)
}
}
override fun <T : Any?> addSource(source: LiveData<T>, onChanged: Observer<in T>) {
throw UnsupportedOperationException()
}
override fun <T : Any?> removeSource(toRemote: LiveData<T>) {
throw UnsupportedOperationException()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment