Android Transformations.switchMap 的理解!
在map()功能
LiveData userLiveData = ...;
LiveData userName = Transformations.map(userLiveData, user -> {
return user.firstName + " " + user.lastName; // Returns String
});
每次的userLiveData的值发生变化,userName将被更新到。请注意,我们正在返回String。
在switchMap()功能:
MutableLiveData userIdLiveData = ...;
LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
repository.getUserById(id)); // Returns LiveData
void setUserId(String userId) {
this.userIdLiveData.setValue(userId);
}
每次的userIdLiveData的值发生变化,repository.getUserById(id)将被调用,就像地图功能。但repository.getUserById(id)返回LiveData。所以每当repository.getUserById(id)返回的LiveData的值发生变化时,userLiveData的值也会改变。所以userLiveData的值将取决于userIdLiveData的变化以及repository.getUserById(id)的值的变化。
LiveData:
内容为T类型数据的容器,可监听内容的变化且具有一定的实时性
对外提供监听容器内容变化的接口observe(LifecycleOwner, Observer)
会在适当的时期通知监听器
适当的时期:激活状态(LifecycleRegistry监听fragment生命周期)
外部需MutableLiveData才能改变容器内容
MutableLiveData:
继承至LiveData
提供改变容器内容的接口setValue/postValue
MediatorLiveData:
继承至MutableLiveData
可监听其他容器内容的变化,通过addSource(source:LiveData, Observer)
addSource还需在激活状态下才会有机会调用addSource中的Observer(激活后,source才会添加Observer作监听器)