【发布时间】:2018-11-29 07:59:55
【问题描述】:
显然,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() 并且不会工作。
有人找到解决办法了吗?
【问题讨论】:
标签: android kotlin android-room android-architecture-components android-livedata