如何以及在哪里使用Transformations.switchMap? [英] How and where to use Transformations.switchMap?

查看:60
本文介绍了如何以及在哪里使用Transformations.switchMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google发布的最新Android体系结构组件库中, Transformations 类中有两个静态函数.虽然 map 函数简单易懂,但我发现很难正确理解 switchMap 函数.

In recent Android Architecture Components library released by Google, we have two static functions in the Transformations class. While the map function is straight forward and easily understandable, I am finding it hard to properly understand the switchMap function.

switchMap的官方文档可以在

The official documentation of switchMap can be found here.

有人可以通过一个实际的例子来解释如何以及在何处使用switchMap函数吗?

Can somebody explain how and where to use the switchMap function with a practical example?

推荐答案

map()函数

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

每次 userLiveData 的值更改时, userName 也会被更新.请注意,我们返回的是 String .

everytime the value of userLiveData changes, userName will be updated too. Notice that we are returning a 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)的值的更改.

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).

switchcode()的实际示例:假设您有一个用户配置文件,该用户配置文件带有跟随"按钮和一个下一个配置文件"按钮,用于设置另一个配置文件信息.下一个配置文件按钮将使用另一个ID调用setUserId(),因此 userLiveData 将会更改,UI也会更改.关注"按钮将调用DAO向该用户添加一个关注者,因此该用户将拥有301个关注者,而不是300个关注者. userLiveData 将具有来自存储库的更新,该更新来自DAO.

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.

这篇关于如何以及在哪里使用Transformations.switchMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆