Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement zip function using LiveData

Tags:

java

android

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

like image 738
marvellousness Avatar asked Mar 18 '26 05:03

marvellousness


1 Answers

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.

like image 98
Saeed Masoumi Avatar answered Mar 19 '26 20:03

Saeed Masoumi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!