How and where to use Transformations.switchMap?

In the recent Android architecture component library released by Google, we have two static functions in the class Transformations. Although the function mapis simple and easy to understand, it is difficult for me to correctly understand the function switchMap.

The official SwitchMap documentation can be found , android.arch.core.util.Function>) rel = noreferrer> here .

Can someone explain how and where to use the switchMap function in a practical example?

+19
source share
4 answers

In map()function

LiveData userLiveData = ...;
LiveData userName = Transformations.map(userLiveData, user -> {
     return user.firstName + " " + user.lastName; // Returns String
});

, userLiveData , userName . , String.

switchMap():

MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
    repository.getUserById(id)); // Returns LiveData

void setUserId(String userId) {
     this.userIdLiveData.setValue(userId);
}

userIdLiveData , userIdLiveData , repository.getUserById(id), map. repository.getUserById(id) LiveData. , LiveData repository.getUserById(id) , userLiveData . , userLiveData userIdLiveData repository.getUserById(id).

switchMap(): , "" " ", . setUserId() , userLiveData . Follow DAO, , 301 300. userLiveData , , DAO.

+31

2 @DamiaFuentes.

MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
repository.getUserById(id)); // Returns LiveData

void setUserId(String userId) {
     this.userIdLiveData.setValue(userId);
}

Transformations.switchMap , userLiveData

+4

, - @DamiaFuentes, :

 MutableLiveData userIdLiveData = ...;
 LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
     repository.getUserById(id));

 void setUserId(String userId) {
      this.userIdLiveData.setValue(userId);
 }

, User (1, "Jane") User (2, "John"), userIdLiveData "1", switchMap getUser (1), LiveData User (1, "Jane"). userLiveData User (1, "Jane"). User (1, "Sarah"), userLiveData User (1, "Sarah").

setUserId userId = "2", userIdLiveData "2" . , userLiveData User (2, ""). LiveData, repository.getUserById(1), .

, userIdLiveData , LiveData, repository.getUserById, "" LiveData.

, : https://developer.android.com/reference/android/arch/lifecycle/Transformations

+1

Source: https://habr.com/ru/post/1690178/


All Articles