android - map() 和 switchMap() 方法有什么区别?

标签 android android-architecture-components android-livedata

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

最佳答案

根据文档

Transformations.map()

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

Transformations.switchMap()

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/

相关文章:

android - 如何更改位图中某些像素的颜色android

java - R 类未生成(API 错误?) - Android 项目

android - Paging库在向上滑动刷新后只调用LoadInitial,不调用LoadAfter

android - 无法创建类 ViewModel 的实例

android - Activity 无法转换为 LifecycleOwner

android-architecture-components - 强制分页库数据源刷新

用于 alpha 测试模式的 Android 应用内购买

android - Titanium - ti.app.proper 的生命周期

android - 房间 "Not sure how to convert a Cursor to this method' s 返回类型": which method?

android - 为什么 LiveData 比 MutableLiveData 更好?