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;
}
}

Parameters
@NonNull Function1<@NonNull X, LiveData<@NonNull Y>> transform

a function to apply to each value set on source to create a new delegate LiveData for the returned one

Returns
@NonNull LiveData<@NonNull Y>

a LiveData mapped from source to type <Y> by delegating to the LiveData returned by applying switchMapFunction to each value set

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2026-01-30 UTC.