我尝试使用LiveData Transformations.map()检查结果并更新UI。但是Transformations.map()回调不会在没有观察者的情况下触发。
那么,在由observeForever {}返回的实时数据上调用是一个很好的方法吗?并在onCleared上删除ViewModel?上的工具。
private lateinit var map: LiveData<Unit>
fun getAppConfiguration(): MutableLiveData<TopRatedMoviesResponse> {
progressDialogVisibleLiveData.postValue(true)
val appConfigurationLiveData = MutableLiveData<TopRatedMoviesResponse>()
val appConfigurationSourceLiveData : MutableLiveData<DataResult> = splashScreenRepository.getAppConfiguration(getApplication())
map = Transformations.map(appConfigurationSourceLiveData) { dataResult ->
progressDialogVisibleLiveData.postValue(false)
when (dataResult) {
is DataResultSuccess -> {
appConfigurationLiveData.postValue(dataResult.data as TopRatedMoviesResponse)
}
is DataResultFailed -> {
when (dataResult.errorCode) {
HTTPError.NO_INTERNET -> {
errorDialogVisibleLiveData.postValue(dataResult)
}
HTTPError.BAD_REQUEST -> {
errorDialogVisibleLiveData.postValue(dataResult)
}
HTTPError.UNAUTHORISED -> {
unAuthorisedEventLiveData.postValue(true)
}
HTTPError.FORBIDDEN, HTTPError.NOT_FOUND, HTTPError.INTERNAL_SERVER_ERROR, HTTPError.UNKNOWN -> {
errorDialogVisibleLiveData.postValue(dataResult)
}
}
}
}
}
map.observeForever { }
return appConfigurationLiveData
}
override fun onCleared() {
super.onCleared()
map.removeObserver { }
}发布于 2019-02-15 14:21:07
但是Transformations.map回调不会在没有观察者的情况下触发。
这是正常的,没有对observerForever()的调用,Transformations.map()返回的LiveData没有任何人提供它保存的数据。
那么,在由observeForever返回的livedata上调用observeForever {}是一种好方法吗?
看一下您在该方法中所做的事情,答案是否定的,这不是使用Transformations.map()的方式。该方法的目标是对源LiveData发出的值进行一些更改,然后将这些值呈现给观察者。在您的示例中,您希望进行简单的类型更改(从dataResult.data到TopRatedMoviesResponse),并在出错时触发一些错误LiveDatas。检查下面的代码:
fun getAppConfiguration(): MutableLiveData<TopRatedMoviesResponse> {
progressDialogVisibleLiveData.postValue(true)
val appConfigurationSourceLiveData : MutableLiveData<DataResult> = splashScreenRepository.getAppConfiguration(getApplication())
return Transformations.map(appConfigurationSourceLiveData) { dataResult ->
progressDialogVisibleLiveData.postValue(false)
when (dataResult) {
is DataResultSuccess -> {
dataResult.data as TopRatedMoviesResponse
}
is DataResultFailed -> {
when (dataResult.errorCode) {
HTTPError.UNAUTHORISED -> {
unAuthorisedEventLiveData.postValue(true)
}
HTTPError.FORBIDDEN, HTTPError.NOT_FOUND, HTTPError.INTERNAL_SERVER_ERROR, HTTPError.UNKNOWN, HTTPError.NO_INTERNET, HTTPError.BAD_REQUEST -> {
errorDialogVisibleLiveData.postValue(dataResult)
}
}
// we have to return something even if an error occured
// I'm returning null, your UI should handle this
null
}
}
}
}还可以查看建筑指南,了解使用LiveData处理数据和错误的其他方法。
https://stackoverflow.com/questions/54708268
复制相似问题