类似于映射,将函数应用于存储在LiveData对象中的值,然后解包并将结果分派到下游. 传递给switchMap()的函数必须返回一个LiveData对象.
换句话说,我可能不是100%正确的,但是如果您熟悉RxJava的话; Transformations#map
有点类似于Observable#map
& Transformations#switchMap
与Observable#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屋!