Search code examples
androidandroid-livedataandroid-architecture-components

Why use Transformations.switchMap?


Is there any advantage in using Transformations.switchMap like this

MutableLiveData<Integer> userId = ...;
LiveData<User> user = Transformations.switchMap(userIdLiveData, id -> repository.getUserById(id));

void setUserId(int userId) {
    // why not query manually here?
    userIdLiveData.setValue(userId);
}

instead of just doing this:

LiveData<User> user;

void setUserId(int userId) {
    user = repository.getUserById(id);
}

Solution

  • Because switchMap "switches" source of data emitted by user LiveData object.

    That means any existing observer of user will seamlessly obtain new user data after you change userId.

    Your second "solution" replaces user LiveData itself so in addition to calling setUserId you will need to manually unregister observers from previous user LiveData and start observing the new one.