Transformations
public final class Transformations
Summary
Public methods |
|
|---|---|
static final @NonNull LiveData<@NonNull X> |
@MainThreadCreates a new |
static final @NonNull LiveData<@NonNull Y> |
@MainThreadReturns a |
static final @NonNull LiveData<@NonNull Y> |
@MainThreadReturns a |
Public methods
distinctUntilChanged
@MainThread
public static final @NonNull LiveData<@NonNull X> <X extends Object> distinctUntilChanged(@NonNull LiveData<@NonNull X> receiver)
Creates a new LiveData object does not emit a value until the source this LiveData value has been changed. The value is considered changed if equals() yields false.
map
@MainThread
public static final @NonNull LiveData<@NonNull Y> <X extends Object, Y extends Object> map(
@NonNull LiveData<@NonNull X> receiver,
@NonNull Function1<@NonNull X, @NonNull Y> transform
)
Returns a LiveData mapped from this LiveData by applying transform to each value set on this LiveData.
This method is analogous to io.reactivex.Observable.map.
transform will be executed on the main thread.
Here is an example mapping a simple User struct in a LiveData to a LiveData containing their full name as a String.
val userLD : LiveData<User> = ...;
val userFullNameLD: LiveData<String> = userLD.map { user -> user.firstName + user.lastName }
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;
}
}