Created
June 17, 2020 08:40
-
-
Save MasterAlish/869b3229ad3cfbf25f10bf98c0b063b4 to your computer and use it in GitHub Desktop.
How to merge two(multiple) liveData? How to combine two 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
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!!)) | |
} | |
} | |
} |
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
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