Created
August 12, 2022 13:54
-
-
Save therealshabi/bd6fc71d7907bc3d0b238179733be992 to your computer and use it in GitHub Desktop.
A utility class to combine 2 LiveData in one, which basically emits value only when both the live data emits some non-null value value
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
package com.magicpin.local.groceryorders; | |
import android.util.Pair; | |
import androidx.lifecycle.LiveData; | |
import androidx.lifecycle.MediatorLiveData; | |
public class CombineLiveData<A, B> { | |
private A lastA = null; | |
private B lastB = null; | |
public LiveData<Pair<A, B>> zipLiveData(LiveData<A> a, LiveData<B> b) { | |
MediatorLiveData<Pair<A, B>> mediatorLiveData = new MediatorLiveData<>(); | |
mediatorLiveData.addSource(a, a1 -> { | |
lastA = a1; | |
update(mediatorLiveData); | |
}); | |
mediatorLiveData.addSource(b, a2 -> { | |
lastB = a2; | |
update(mediatorLiveData); | |
}); | |
return mediatorLiveData; | |
} | |
private void update(MediatorLiveData<Pair<A, B>> mediatorLiveData) { | |
A localLastA = lastA; | |
B localLastB = lastB; | |
if (localLastA != null && localLastB != null) | |
mediatorLiveData.setValue(new Pair<>(localLastA, localLastB)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment