官方文档中的介绍
在Android Developer官网上,对于map和switchMap的解释是这样的:
- map:
Applies a function on the value stored in the LiveData object, and propagates the result downstream.
对存储在 LiveData 对象中的值应用函数,并将结果传播到下游。
- switchMap:
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, as illustrated by the following example:
对存储在 LiveData 对象中的值应用函数,并将结果解封和分派到下游。传递给 switchMap() 的函数必须返回 LiveData 对象。
其实单纯的看上面两个官方文档反而还会觉得更加的莫名其妙。其实这两句话差异的核心在于 “解封” 和 “返回LiveData对象” 。
例子
我们先来举个栗子来说明下这两个方法的区别(例子来源于此文章):
class TransformationMapFragment : Fragment() {
private val changeObserver = Observer<String> {
value ->
value?.let {
txt_fragment