public final class Transformations
Summary
Public methods
switchMap
@MainThread
public static final @NonNull LiveData<@NonNull Y> <X extends Object, Y extends Object> switchMap(
@NonNull LiveData<@NonNull X> receiver,
@NonNull Function1<@NonNull X, LiveData<@NonNull Y>> transform
)
Returns a LiveData mapped from the input this LiveData by applying transform to each value set on this.
The returned `LiveData` delegates to the most recent `LiveData` created by [transform] with the most recent value set to `this`, without changing the reference. In this way [transform] can change the 'backing' `LiveData` transparently to any observer registered to the `LiveData` returned by `switchMap()`.
Note that when the backing LiveData is switched, no further values from the older LiveData will be set to the output LiveData. In this way, the method is analogous to io.reactivex.Observable.switchMap.
transform will be executed on the main thread.
Here is an example class that holds a typed-in name of a user String (such as from an EditText) in a MutableLiveData and returns a LiveData containing a List of User objects for users that have that name. It populates that LiveData by requerying a repository-pattern object each time the typed name changes.
This `ViewModel` would permit the observing UI to update "live" as the user ID text changes.
class UserViewModel: AndroidViewModel {
val nameQueryLiveData : MutableLiveData<String> = ...fun usersWithNameLiveData(): LiveData<List<String>> = nameQueryLiveData.switchMap {
name -> myDataSource.usersWithNameLiveData(name)
}fun setNameQuery(val name: String) {
this.nameQueryLiveData.value = name;
}
}