尤其是我的存储库中有这些LiveData对象
val liveDataA : MutableLiveData<List<ProfileApiData.A>> = MutableLiveData()
val liveDataB : MutableLiveData<List<ProfileApiData.B>> = MutableLiveData()
val liveDataC : MutableLiveData<ProfileApiData.C?> = MutableLiveData()
...我打算在所述存储库中使用以下方法进行更新。
suspend fun fetchProfile() {
val profileDataApi = userApi.getProfile()
liveDataA.postValue( profileDataApi.a )
liveDataB.postValue( profileDataApi.b )
liveDataC.postValue( profileDataApi.c )
dao.insertProfile(profileDataApi.asEntity)
}
在引用它的ViewModel中,我使用了以下方法:
private fun getLiveDataAAsEntities() : LiveData<List<AEntity>> {
return Transformations.map(userRepository.liveDataA) {
val entities = it.entities
liveDataARVDataSource.swapData( entities )
Trace.i("A map result ${entities.size}")
return@map entities
}
}
private fun getLiveDataBAsEntities() : LiveData<List<BEntity>> {
return Transformations.map(userRepository.liveDataB) {
val entities = it.entities
liveDataBRVDataSource.swapData( entities )
Trace.i("B map result ${entities.size}")
return@map entities
}
}
private fun getLiveDataCAsEntity() : LiveData<ProfileApiData.CEntity?> {
return Transformations.map(userRepository.liveDataC) {
Trace.i("C map result $it")
if (it?.url.isEmpty) {
presenters.forEach {
it.onLiveDataCParsed(false, "", -1, -1, "", "")
}
} else {
it?.let { entityC ->
presenters.forEach {
it.onLiveDataCParsed(true, entityC.url, entityC.stamp.countAllStamp, entityC.stamp.sisa, entityC.stamp.prize, entityC.dashCoverUrl)
}
}
}
return@map it
}
}
fun updateProfile() {
viewModelScope.launch(Dispatchers.Main) {
val updateProfileTask = async(Dispatchers.IO) {
Trace.i("start fetch profile")
userRepository.fetchProfile()
}
updateProfileTask.await()
liveDataAEntity = getLiveDataAAsEntities()
liveDataBEntity = getLiveDataBAsEntities()
liveDataCEntity = getLiveDataCAsEntities()
Trace.i("finished fetch profile ${userRepository.liveSchedules.value} ${liveSchedules.value}\n$${movies.value}\n${userRepository.hutPlaydayObject.value} ${hutPlaydayObject.value}")
presenters.forEach {
it.onUpdateProfileFinished()
}
}
}
...以“观察”存储库中的liveDataA,liveDataB和liveDataC。注意:.entities
是自定义地图函数。
但是,finished fetch profile
日志值仍然返回null,甚至没有调用map函数中的日志函数。
这种Transformations.map
的实现有问题吗?