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

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

问题描述

LiveData类的这两种方法之间有什么区别?官方文档和教程对此含糊不清.在 map()方法中,第一个参数称为 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?

推荐答案

根据文档

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

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

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

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

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#flatMap.

让我们举个例子,有一个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的函数仅返回字符串,但最终返回LiveData的是Transformation#map.

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,它是您正在转换的 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天全站免登陆