在 Google 最近发布的 Android 架构组件库中,我们在 Transformations
类中有两个静态函数。虽然 map
函数直截了当且易于理解,但我发现很难正确理解 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)
,就像 map 函数一样。但是 repository.getUserById(id)
返回一个 LiveData
。所以每次repository.getUserById(id)
返回的LiveData
的值发生变化,userLiveData
的值也会发生变化。所以 userLiveData
的值将取决于 userIdLiveData
的变化和 repository.getUserById(id)
的值的变化。
switchMap()
的实际示例:假设您有一个用户配置文件,其中包含一个关注按钮和一个设置另一个配置文件信息的下一个配置文件按钮。下一个配置文件按钮将使用另一个 ID 调用 setUserId(),因此 userLiveData
将发生变化,UI 也会发生变化。关注按钮将调用 DAO 为该用户再添加一个关注者,因此该用户将拥有 301 个关注者而不是 300 个。userLiveData
将获得来自存储库的此更新,该更新来自 DAO。
关于android - 如何以及在何处使用 Transformations.switchMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610676/