Class provides methods for feature composition and delegation of LiveData instances. Similar to kotlin's by, but the latter is obviously simpler.
These transformations are computationally lazy and run only when the returned LiveData is observed.
map
I should call this method mapping, which is to link the two values of X and Y type, and pass the value of X to y.
public static <X, Y> LiveData<Y> map( @NonNull LiveData<X> source, //X observed, Y observed @NonNull final Function<X, Y> mapFunction) { final MediatorLiveData<Y> result = new MediatorLiveData<>();//A MediatorLiveData of type Y result.addSource(source, new Observer<X>() { //Add observed X to Y @Override public void onChanged(@Nullable X x) { result.setValue(mapFunction.apply(x)); //When onChanged is called, the value of X is passed to Y } }); return result; }
switchMap
Switch mapping, that is to say, judge the observed, and if it is not the same, replace it with a new one.
public static <X, Y> LiveData<Y> switchMap( @NonNull LiveData<X> source, @NonNull final Function<X, LiveData<Y>> switchMapFunction) { final MediatorLiveData<Y> result = new MediatorLiveData<>();//Same as above result.addSource(source, new Observer<X>() { LiveData<Y> mSource; public void onChanged(@Nullable X x) { LiveData<Y> newLiveData = switchMapFunction.apply(x); if (mSource == newLiveData) {return;} //Used, already exists, return if (mSource != null) { result.removeSource(mSource); }//Source exists, remove it mSource = newLiveData; if (mSource != null) { //Transmit data result.addSource(mSource,(Observer)(Y)-> { result.setValue(y);} }); } } }); return result; }
The returned LiveData is delegated to the LiveData recently created by calling switchMapFunction. If it has been used recently and is the same, the reference will not be changed. In this way, the switchMapFunction can change the observed transparently. When you switch the LiveData of the observed, the previous value will not be output.
summary
In short, with this class, you can create and return a node of LiveData.