+-
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(),并且不起作用.

有没有人为此找到解决方案?

最佳答案
叫我疯了,但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,只需写入您的数据库.

点击查看更多相关文章

转载注明原文:android – 将LiveData转换为MutableLiveData - 乐贴网