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对象
data.observe(viewLifecycleOwner, Observer{
//监听LiveData对象需要不停的解绑,重新绑定,效率低
})
每次调用queryPlaces()方法生成的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中创建,而是调用其他方法创建的。