Skip to content

Instantly share code, notes, and snippets.

@webserveis
Last active March 5, 2019 21:13
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 webserveis/3d6206e978086cb1497767c19b6fa4dd to your computer and use it in GitHub Desktop.
Save webserveis/3d6206e978086cb1497767c19b6fa4dd to your computer and use it in GitHub Desktop.
Combine MediatorLiveData
/*
https://stackoverflow.com/questions/49493772/mediatorlivedata-or-switchmap-transformation-with-multiple-parameters
https://medium.com/@BladeCoder/to-implement-a-manual-refresh-without-modifying-your-existing-livedata-logic-i-suggest-that-your-7db1b8414c0e
https://coredump.uno/questions/48769812/best-practice-runtime-filters-with-room-and-livedata
https://www.e-learn.cn/content/wangluowenzhang/1592769
https://coredump.uno/questions/49493772/mediatorlivedata-or-switchmap-transformation-with-multiple-parameters
*/
public class LiveDataUtil2<A, B, C, Y> {
public interface Thunk2<A, B, C, Y> {
LiveData<Y> apply(A a, B b, C c);
}
LiveData<Y> mSource;
@MainThread
public LiveData<Y> switchMap(LiveData<A> trigger1, LiveData<B> trigger2,
LiveData<C> trigger3, final Thunk2 thunk) {
final MediatorLiveData<Y> result = new MediatorLiveData();
result.addSource(trigger1, new Observer<A>() {
public void onChanged(@Nullable A a) {
LiveData<Y> newLiveData = thunk.apply(trigger1.getValue(), trigger2.getValue(), trigger3.getValue());
if(mSource != newLiveData) {
if(mSource != null) {
result.removeSource(mSource);
}
mSource = newLiveData;
if(mSource != null) {
result.addSource(mSource, new Observer<Y>() {
public void onChanged(@Nullable Y y) {
result.setValue(y);
}
});
}
}
}
});
result.addSource(trigger2, new Observer<B>() {
public void onChanged(@Nullable B b) {
LiveData<Y> newLiveData = thunk.apply(trigger1.getValue(), trigger2.getValue(), trigger3.getValue());
if(mSource != newLiveData) {
if(mSource != null) {
result.removeSource(mSource);
}
mSource = newLiveData;
if(mSource != null) {
result.addSource(mSource, new Observer<Y>() {
public void onChanged(@Nullable Y y) {
result.setValue(y);
}
});
}
}
}
});
result.addSource(trigger3, new Observer<C>() {
public void onChanged(@Nullable C c) {
LiveData<Y> newLiveData = thunk.apply(trigger1.getValue(), trigger2.getValue(), trigger3.getValue());
if(mSource != newLiveData) {
if(mSource != null) {
result.removeSource(mSource);
}
mSource = newLiveData;
if(mSource != null) {
result.addSource(mSource, new Observer<Y>() {
public void onChanged(@Nullable Y y) {
result.setValue(y);
}
});
}
}
}
});
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment