-
-
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.
This file contains hidden or 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
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