In recent Android Architecture Components library released by Google, we have two static functions in the Transformations
class. While the map
function
For those who want more explanation of @DamiaFuentes switchmap() function example given below:
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
repository.getUserById(id));
void setUserId(String userId) {
this.userIdLiveData.setValue(userId);
}
In a scenario where the repository contains User(1, "Jane") and User(2, "John"), when the userIdLiveData value is set to "1", the switchMap will call getUser(1), that will return a LiveData containing the value User(1, "Jane"). So now, the userLiveData will emit User(1, "Jane"). When the user in the repository gets updated to User(1, "Sarah"), the userLiveData gets automatically notified and will emit User(1, "Sarah").
When the setUserId method is called with userId = "2", the value of the userIdLiveData changes and automatically triggers a request for getting the user with id "2" from the repository. So, the userLiveData emits User(2, "John"). The LiveData returned by repository.getUserById(1) is removed as a source.
From this example, we can understand that the userIdLiveData is the trigger and the LiveData returned by the repository.getUserById is the "backing" LiveData.
For more reference, check out: https://developer.android.com/reference/android/arch/lifecycle/Transformations