gpt4 book ai didi

android - 将 LiveData 转换为 MutableLiveData

转载 作者:IT老高 更新时间:2023-10-28 13:41:24 24 4
gpt4 key购买 nike

显然,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()
}
}
}

这样,我从数据库获取更新,可以保存 Profile 对象,但我不能修改属性。

例如:mutableLiveData.value = Profile() 会起作用。mutableLiveData.value.userName = "name" 会调用 getValue() 而不是 postValue() 并且不起作用。

有人找到解决方案了吗?

最佳答案

说我疯了,但 AFAIK 没有理由为您从 DAO 收到的对象使用 MutableLiveData。

这个想法是您可以通过 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 后发出。

dao.insert(profile); // this will make LiveData emit again

所以没有理由使用 getValue/setValue ,只需写入您的数据库即可。

关于android - 将 LiveData 转换为 MutableLiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50943919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com