如何以及在哪里使用Transformations.switchMap?
在Google发布的最新Android Architecture Components库中,我们在Transformations类中有两个静态函数。虽然map功能较为简单,并容易理解的,我发现很难正确理解switchMap功能。如何以及在哪里使用Transformations.switchMap?
switchMap的官方文档可以找到here。
有人可以解释如何以及在哪里使用switchMap函数和一个实际的例子?
回答:
在map()功能
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的值发生变化,repository.getUserById(id)将被调用,就像地图功能。但repository.getUserById(id)返回LiveData。所以每当repository.getUserById(id)返回的LiveData的值发生变化时,userLiveData的值也会改变。所以userLiveData的值将取决于userIdLiveData的变化以及repository.getUserById(id)的值的变化。
switchMap()的实际示例:假设您有一个用户配置文件,其中包含一个关注按钮和一个用于设置其他配置文件信息的下一个配置文件按钮。下一个配置文件按钮将调用setUserId()与另一个ID,所以userLiveData将改变,用户界面将改变。 Follow按钮会调用DAO为该用户添加一个追随者,因此用户将拥有301个追随者而不是300个。userLiveData将具有来自DAO的存储库的此更新。
以上是 如何以及在哪里使用Transformations.switchMap? 的全部内容, 来源链接: utcz.com/qa/257541.html
