LiveData 类的这两种方法有什么区别?官方文档和教程对此非常模糊。在 map() 方法中,第一个参数称为 source,但在 switchMap() 中,它称为 trigger。这背后的原因是什么?
最佳答案
根据文档
Applies a function on the value stored in the LiveData object, and propagates the result downstream.
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.
换句话说,如果你熟悉 RxJava,我可能不是 100% 正确的; Transformations#map
有点类似于 Observable#map
& Transformations#switchMap
类似于 Observable#switchMap
。
举个例子,有一个 LiveData 发出一个字符串,我们想用大写字母显示该字符串。
一种方法如下;在 Activity 或 fragment 中
Transformations.map(stringsLiveData, String::toUpperCase)
.observe(this, textView::setText);
传递给 map
的函数只返回一个字符串,但它是 Transformation#map
最终返回一个 LiveData
。
第二种方法;在 Activity 或 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 对象。
因此,对于 map
它是您正在转换的 source LiveData
而对于 switchMap
传递的 LiveData
将充当 trigger,在打开包装并将结果发送到下游后,它将切换到另一个 LiveData
。
关于android - map() 和 switchMap() 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575961/