两种转化LiveData对象的方法:map()和switchMap()

Map()

public static LiveData<Y> map (LiveData<X> source, 
                Function<X, Y> mapFunction)

此函数接收两个参数,第一个参数是用于转换的LiveData原始对象,第二个参数是转换函数

举例如下:

假设现在有一个User类,属性包括firstName,lastName,age。

data class User(var firstName: String, var lastName: String, var age: Int)

在ViewModel中创建一个User类型的LiveData对象。

val userLiveData = MutableLiveData<User>()

但是不需要将用户的age展示出来,此时就可以通过Transformations.map()创建一个新的LiveData对象。

    val userName:LiveData<String> = Transformations.map(userLiveData) {
        user->
        "${user.firstName} ${user.lastName}"//封装数据
    }

然后就可以直接监听这个新的LiveData对象。

        viewModel = ViewModelProvider(this).get(MapTestViewModel::class.java)
        viewModel.userName.observe(this, Observer {
                string->
                text.text = string
        })

Map()函数可以用于对数据的封装

SwitchMap()

public static LiveData<Y> switchMap (LiveData<X> source, 
                Function<X, LiveData<Y>> switchMapFunction)

switchMap()函数同样接收两个参数,第一个参数是一个LiveData对象,当此LivaData对象变化时就调用转换函数生成一新的LiveData对象,第二个参数就是转化函数。
switchMap()函数可用于LiveData对象不是直接在ViewModel中创建,而是调用其他方法创建的。

	private val queryLiveData = MutableLiveData<String>()   //直接创建

    fun queryPlaces(name: String):LiveData<Result<List<Place>>>{
        return Repository.searchPlaces(name)
    }//利用其他方法创建

举例如下:

class PlaceViewModel: ViewModel() {
    fun queryPlaces(name: String): LiveData<Result<List<Place>>>{
        return Repository.searchPlaces(name)
    }
}

在ViewModel中有一个queryPlaces()方法,该方法产生一个LiveData对象,现在要监听这个对象,代码如下

val data = viewModel.queryPlaces(text)  //每次调用该方法都会产生新的LiveData对象,无法监听原来的LiveData对象
data.observe(viewLifecycleOwner, Observer{   
   
})

每次调用queryPlaces()方法生成的LiveData对象都是一个新的对象,无法监听原来的LiveData对象。此时就可以用swithMap()方法创建一个可观察的,不会改变的LiveData对象
但是需要在ViewModel中多创建一个LiveData对象,用于监听数据变化。当LiveData的值变化时就会触发转化函数

class PlaceViewModel: ViewModel() {
    private val queryLiveData = MutableLiveData<String>()

    fun queryPlaces(name: String){
        queryLiveData.value = name
    }

    val placesLiveData = Transformations.switchMap(queryLiveData){
    //当queryLiveData的值变化时就会触发转化函数
            name->
            Repository.searchPlaces(name)
    }
}

观察placesLiveData对象

viewModel.placesLiveData.observe(viewLifecycleOwner, Observer {
//此时的LiveData对象不会改变
})

此时观察的LiveData对象不会改变,也就不用解除绑定,重新绑定了。

switchMap()函数可用于LiveData对象不是直接在ViewModel中创建,而是调用其他方法创建的。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值