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);
}
Because
switchMap"switches" source of data emitted byuserLiveData object.That means any existing observer of
userwill seamlessly obtain new user data after you changeuserId.Your second "solution" replaces
userLiveData itself so in addition to callingsetUserIdyou will need to manually unregister observers from previoususerLiveData and start observing the new one.