map() 和 switchMap() 方法有什么区别? [英] What is the difference between map() and switchMap() methods?

查看:63
本文介绍了map() 和 switchMap() 方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LiveData 类的这两种方法有什么区别?官方文档和教程对此非常模糊.在ma​​p() 方法中,第一个参数称为source,但在switchMap() 中,它称为trigger.这背后的原理是什么?

What is the difference between those 2 methods of the LiveData class? The official doc and tutorial are pretty vague on that. In the map() method the first parameter called source but in the switchMap() it called trigger. What's the rationale behind that?

推荐答案

根据文档

Transformations.map()

对存储在 LiveData 对象中的值应用函数,并将结果传播到下游.

Applies a function on the value stored in the LiveData object, and propagates the result downstream.

Transformations.switchMap()

与 map 类似,将函数应用于存储在 LiveData 对象中的值,并将结果解包并分派到下游.传递给 switchMap() 的函数必须返回一个 LiveData 对象.

Similar to map, applies a function to the value stored in the LiveData object and unwraps and dispatches the result downstream. The function passed to switchMap() must return a LiveData object.

换句话说,我可能不是 100% 正确,但如果您熟悉 RxJava;Transformations#map 有点类似于 Observable#map &Transformations#switchMap 类似于 Observable#switchMap.

In other words, I may not be 100% correct but if you are familiar with RxJava; Transformations#map is kind of similar to Observable#map & Transformations#switchMap is similar to Observable#switchMap.

举个例子,有一个 LiveData 发出一个字符串,我们想用大写字母显示该字符串.

Let's take an example, there is a LiveData which emits a string and we want to display that string in capital letters.

一种方法如下;在活动或片段中

One approach would be as follows; in an activity or fragment

Transformations.map(stringsLiveData, String::toUpperCase)
    .observe(this, textView::setText);

传递给 map 的函数只返回一个字符串,但 Transformation#map 最终返回一个 LiveData.

the function passed to the map returns a string only, but it's the Transformation#map which ultimately returns a LiveData.

第二种方法;在活动或片段中

The second approach; in an activity or fragment

Transformations.switchMap(stringsLiveData, this::getUpperCaseStringLiveData)
            .observe(this, textView::setText);

private LiveData<String> getUpperCaseStringLiveData(String str) {
    MutableLiveData<String> liveData = new MutableLiveData<>();
    liveData.setValue(str.toUpperCase());
    return liveData;
}

如果您看到 Transformations#switchMap 实际上已经切换了 LiveData.因此,再次根据文档传递给 switchMap() 的函数必须返回一个 LiveData 对象.

If you see Transformations#switchMap has actually switched the LiveData. So, again as per the documentation The function passed to switchMap() must return a LiveData object.

因此,在 map 的情况下,它是您正在转换的 source LiveData,在 switchMap 的情况下传递的 LiveData 将充当 触发器,在将结果解包并向下游分派后,它将切换到另一个 LiveData.

So, in case of map it is the source LiveData you are transforming and in case of switchMap the passed LiveData will act as a trigger on which it will switch to another LiveData after unwrapping and dispatching the result downstream.

这篇关于map() 和 switchMap() 方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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