Skip to content

Instantly share code, notes, and snippets.

@MasterAlish
Created June 17, 2020 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MasterAlish/869b3229ad3cfbf25f10bf98c0b063b4 to your computer and use it in GitHub Desktop.
Save MasterAlish/869b3229ad3cfbf25f10bf98c0b063b4 to your computer and use it in GitHub Desktop.
How to merge two(multiple) liveData? How to combine two LiveData?
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
class MergedLiveData<T1, T2>(
private val liveData1: LiveData<T1>,
private val liveData2: LiveData<T2>
) : LiveData<Pair<T1, T2>>() {
private var value1: T1? = null
private var value2: T2? = null
private val observer1 = Observer<T1> {
value1 = it
invalidate()
}
private val observer2 = Observer<T2> {
value2 = it
invalidate()
}
override fun observe(owner: LifecycleOwner, observer: Observer<in Pair<T1, T2>>) {
super.observe(owner, observer)
liveData1.observe(owner, observer1)
liveData2.observe(owner, observer2)
}
private fun invalidate() {
if (value1 != null && value2 != null) {
postValue(Pair(value1!!, value2!!))
}
}
}
import com.example.livedata.MergedLiveData
// ...
fun someMethod(){
MergedLiveData(someLiveData, anotherLiveData).observe(this, Observer {
doSmthWithMultipleValues(it.first, it.second)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment