How and where to use Transformations.switchMap?

后端 未结 4 1213
渐次进展
渐次进展 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:33

    Adding my 2 cents to @DamiaFuentes answer.

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

    Transformations.switchMap method will only be called when you have at least one observer for userLiveData

提交回复
热议问题