在谷歌最近发布的安卓架构组件库中,我们在Transformations类中有两个静态函数。虽然map函数简单易懂,但我发现很难正确理解switchMap函数。
有没有人能用一个实际的例子来解释一下如何以及在哪里使用switchMap函数?
发布于 2017-12-06 22:28:54
在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()的实际示例:假设您有一个用户配置文件,其中有一个follow按钮和一个next profile按钮,后者设置另一个配置文件信息。Next profile按钮将使用另一个id调用setUserId(),因此userLiveData将更改,UI也将更改。Follow按钮将调用DAO为该用户添加多一个关注者,因此该用户将拥有301个关注者,而不是300个。userLiveData将拥有来自存储库的更新,该存储库来自DAO。
发布于 2018-05-26 00:05:16
将我的2美分添加到@DamiaFuentes的答案中。
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
repository.getUserById(id)); // Returns LiveData
void setUserId(String userId) {
this.userIdLiveData.setValue(userId);
}仅当至少有一个userLiveData观察者时,才会调用Transformations.switchMap方法
发布于 2018-10-31 12:07:14
对于那些想要更多地解释@DamiaFuentes switchmap()函数的人,下面给出了一个例子:
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
repository.getUserById(id));
void setUserId(String userId) {
this.userIdLiveData.setValue(userId);
}在存储库包含用户(1,"Jane")和用户(2,"John")的场景中,当userIdLiveData值设置为"1“时,switchMap将调用getUser(1),这将返回值为User(1,"Jane")的LiveData。现在,userLiveData将发出User(1,"Jane")。当存储库中的用户更新为User(1,"Sarah")时,userLiveData会自动收到通知,并发出User(1,"Sarah")。
当使用userId = "2“调用setUserId方法时,userIdLiveData的值会发生变化,并自动触发从存储库获取id为"2”的用户的请求。因此,userLiveData发出User(2,"John")。repository.getUserById(1)返回的LiveData已作为源删除。
从这个例子中,我们可以理解userIdLiveData是触发器,repository.getUserById返回的LiveData是“支持”LiveData。
有关更多参考信息,请查看:https://developer.android.com/reference/android/arch/lifecycle/Transformations
https://stackoverflow.com/questions/47610676
复制相似问题