Skip to content

Instantly share code, notes, and snippets.

@therealshabi
Created August 12, 2022 13:54
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 therealshabi/bd6fc71d7907bc3d0b238179733be992 to your computer and use it in GitHub Desktop.
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
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