android – 将LiveData转换为MutableLiveData

weixin_38050323 2019-09-12 12:16:41
显然,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(),并且不起作用. 有没有人为此找到解决方案?
...全文
135 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38056873 2019-09-12
  • 打赏
  • 举报
回复
叫我疯了,但AFAIK没有理由将MutableLiveData用于从DAO收到的对象. 我们的想法是您可以通过LiveData< List< T>>公开对象. @Dao public interface ProfileDao { @Query("SELECT * FROM PROFILE") LiveData<List<Profile>> getProfiles(); } 现在你可以观察它们: profilesLiveData.observe(this, (profiles) -> { if(profiles == null) return; // you now have access to profiles, can even save them to the side and stuff this.profiles = profiles; }); 因此,如果要使此实时数据“发出新数据并对其进行修改”,则需要将配置文件插入数据库. write将重新评估此查询,并在将新的配置文件值写入db后将其发出. dao.insert(profile); // this will make LiveData emit again 因此没有理由使用getValue / setValue,只需写入您的数据库.

435

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧