Why use Transformations.switchMap?

55 Views Asked by At

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

There are 1 best solutions below

0
Pawel On BEST ANSWER

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.