android – 将LiveData转换为MutableLiveData
显然,Room无法处理MutableLiveData,我们必须坚持使用LiveData,因为它返回以下错误:
error: Not sure how to convert a Cursor to this method's return type
我用这种方式在我的数据库助手中创建了一个“自定义”MutableLiveData:
class ProfileRepository @Inject internal constructor(private val profileDao: ProfileDao): ProfileRepo{
override fun insertProfile(profile: Profile){
profileDao.insertProfile(profile)
}
val mutableLiveData by lazy { MutableProfileLiveData() }
override fun loadMutableProfileLiveData(): MutableLiveData<Profile> = mutableLiveData
inner class MutableProfileLiveData: MutableLiveData<Profile>(){
override fun postValue(value: Profile?) {
value?.let { insertProfile(it) }
super.postValue(value)
}
override fun setValue(value: Profile?) {
value?.let { insertProfile(it) }
super.setValue(value)
}
override fun getValue(): Profile? {
return profileDao.loadProfileLiveData().getValue()
}
}
}
这样,我从DB获取更新并可以保存Profile对象,但我无法修改属性.
例如:mutableLiveData.value = Profile()可以工作.mutableLiveData.value.userName =“name”将调用getValue()而不是postValue(),并且不起作用.
有没有人为此找到解决方案?