android - 如何以及在何处使用 Transformations.switchMap?

标签 android android-architecture-components android-livedata

在 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/

相关文章:

android - 带有分页架构组件的初始占位符

android - SingleLiveEvent 实际上是 Android 架构组件库的一部分吗?

android - 如何更改 LiveData 的值而不通知观察者

android - 数据显示为空但url在Postman上有效

Android:通过代码动态关闭虚拟键盘?

安卓 MVVM : How to handle network request failiures?

android - 强制 fragment 内的 LiveData Observer 在再次可见后接收更改?

android - 仅通过当前数据使用 MediatorLiveData 的最佳实践

java - 使用显式 Intent 时应用程序崩溃

android - 刷新折线和标记而不闪烁