将LiveData转换为MutableLiveData [英] Convert LiveData to MutableLiveData
问题描述
显然,Room无法处理MutableLiveData,我们必须坚持使用LiveData,因为它会返回以下错误:
Apparently, Room is not able to handle MutableLiveData and we have to stick to LiveData as it returns the following error:
error: Not sure how to convert a Cursor to this method's return type
我通过这种方式在数据库帮助器中创建了一个自定义" MutableLiveData:
I created a "custom" MutableLiveData in my DB helper this way:
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()
}
}
}
这样,我从数据库获取更新并可以保存Profile
对象,但是我不能修改属性.
This way, I get the updates from DB and can save the Profile
object but I cannot modify attributes.
例如:
mutableLiveData.value = Profile()
可以工作.
mutableLiveData.value.userName = "name"
会调用getValue()
而不是postValue()
,并且不起作用.
For example:
mutableLiveData.value = Profile()
would work.
mutableLiveData.value.userName = "name"
would call getValue()
instead postValue()
and wouldn't work.
有人找到解决方案了吗?
Did anyone find a solution for this?
推荐答案
叫我疯了,但AFAIK没有理由为从DAO接收的对象使用MutableLiveData.
Call me crazy but AFAIK there is zero reason to use a MutableLiveData for the object that you received from the 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;
});
因此,如果要使此实时数据发出新数据并对其进行修改",则需要将概要文件插入数据库中.写入操作将重新评估该查询,并且将新的配置文件值写入db后将发出该查询.
So if you want to make this live data "emit a new data and modify it", then you need to insert the profile into the database. The write will re-evaluate this query and it will be emitted once the new profile value is written to db.
dao.insert(profile); // this will make LiveData emit again
因此,没有理由使用getValue
/setValue
,只需写入数据库即可.
So there is no reason to use getValue
/setValue
, just write to your db.
这篇关于将LiveData转换为MutableLiveData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!