I'm using twos LiveDatas to get data from my server, and want to result after both LiveData finished?
LiveData live1 = ...;
LiveData live2 = ...;
MutableLiveData live3 = ...;
live1.observe(this, value -> {
live3.postValue(value);
});
live2.observe(this, value -> {
live3.postValue(value);
});
live3.observe(this, value -> {
// TODO: Get both values from live1, live2
}
I expect the both values from live1 and live2
What you need is called zip function:
fun <A, B> zip(first: LiveData<A>, second: LiveData<B>): LiveData<Pair<A, B>> {
val mediatorLiveData = MediatorLiveData<Pair<A, B>>()
var isFirstEmitted = false
var isSecondEmitted = false
var firstValue: A? = null
var secondValue: B? = null
mediatorLiveData.addSource(first) {
isFirstEmitted = true
firstValue = it
if (isSecondEmitted) {
mediatorLiveData.value = Pair(firstValue!!, secondValue!!)
isFirstEmitted = false
isSecondEmitted = false
}
}
mediatorLiveData.addSource(second) {
isSecondEmitted = true
secondValue = it
if (isFirstEmitted) {
mediatorLiveData.value = Pair(firstValue!!, secondValue!!)
isFirstEmitted = false
isSecondEmitted = false
}
}
return mediatorLiveData
}
Now, you can call zip(firstLiveData,secondLiveData) and observe on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With