Last active
December 7, 2018 12:44
-
-
Save jutikorn/8048ea3ad079de8530974af681deb80d to your computer and use it in GitHub Desktop.
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
@MainThread | |
public static <X, Y> LiveData<Y> map(@NonNull LiveData<X> source, | |
@NonNull final Function<X, Y> func) { | |
final MediatorLiveData<Y> result = new MediatorLiveData<>(); | |
result.addSource(source, new Observer<X>() { | |
@Override | |
public void onChanged(@Nullable X x) { | |
result.setValue(func.apply(x)); | |
} | |
}); | |
return result; | |
} | |
@MainThread | |
public static <X, Y> LiveData<Y> switchMap(@NonNull LiveData<X> trigger, | |
@NonNull final Function<X, LiveData<Y>> func) { | |
final MediatorLiveData<Y> result = new MediatorLiveData<>(); | |
result.addSource(trigger, new Observer<X>() { | |
LiveData<Y> mSource; | |
@Override | |
public void onChanged(@Nullable X x) { | |
LiveData<Y> newLiveData = func.apply(x); | |
if (mSource == newLiveData) { | |
return; | |
} | |
if (mSource != null) { | |
result.removeSource(mSource); | |
} | |
mSource = newLiveData; | |
if (mSource != null) { | |
result.addSource(mSource, new Observer<Y>() { | |
@Override | |
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