How and where to use Transformations.switchMap?

后端 未结 4 1215
渐次进展
渐次进展 2021-01-29 21:14

In recent Android Architecture Components library released by Google, we have two static functions in the Transformations class. While the map function

4条回答
  •  無奈伤痛
    2021-01-29 21:48

    In the map() function

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

    everytime the value of userLiveData changes, userName will be updated too. Notice that we are returning a String.

    In the switchMap() function:

    MutableLiveData userIdLiveData = ...;
    LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
        repository.getUserById(id)); // Returns LiveData
    
    void setUserId(String userId) {
         this.userIdLiveData.setValue(userId);
    }
    

    everytime the value of userIdLiveData changes, repository.getUserById(id) will be called, just like the map function. But repository.getUserById(id) returns a LiveData. So everytime that the value of the LiveData returned by repository.getUserById(id) changes, the value of userLiveData will change too. So the value of userLiveData will depend on changes of userIdLiveData and changes of the value of repository.getUserById(id).

    Practical example of switchMap(): imagine you have a user profile with a follow button and a next profile button which sets another profile info. Next profile button will call setUserId() with another id so userLiveData will change and UI will change. Follow button will call the DAO to add one follower more to that user, so the user will have 301 followers instead of 300. userLiveData will have this update that comes from the repository, which comes from the DAO.

提交回复
热议问题