将LiveData转换为MutableLiveData

问题描述 投票:7回答:3

显然,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
3个回答
8
投票

叫我疯了,但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,只需写入您的数据库。


1
投票

由于Room不支持MutableLiveData并且仅支持LiveData,因此您创建包装器的方法是我能想到的最佳方法。由于GoogleMutableLiveData方法是setValuepostValue支持qazxswpo将是复杂的。在public,他们是LiveData,它提供更多的控制。


1
投票

在您的存储库中,您可以获取protected并将其转换为LiveData

MutableLivedata
© www.soinside.com 2019 - 2024. All rights reserved.