[英]Android: Setting LiveData as MutableLiveData
Firstly i might not actually be understanding what mutable live data is correctly.首先,我可能实际上并没有理解什么是可变的实时数据是正确的。
i get data from room using live data and then show it to the UI, it is a question with answers, so at the end of the question i would like to update the database with correct answers, the time it took etc etc.我使用实时数据从房间获取数据,然后将其显示给用户界面,这是一个有答案的问题,所以在问题结束时,我想用正确的答案、花费的时间等更新数据库。
I cannot work out how to use Mutable live data as there is next to no useful information on it or i'm incredibly stupid!我不知道如何使用可变实时数据,因为几乎没有关于它的有用信息,或者我非常愚蠢!
So firstly, can i actually update the database with mutable live data?所以首先,我真的可以用可变的实时数据更新数据库吗?
if so how?如果是这样怎么办? (i don't like asking this but i am a really stumped)
(我不喜欢问这个,但我真的很难过)
Dao道
@Query("SELECT * FROM question_table WHERE :id = uoe_id")
LiveData<Question> getQuestionLiveData(int id);
Repo回购
public LiveData<Question> getQuestionLiveData(int id) {
return questionDao.getQuestionLiveData(id);
}
ViewModel视图模型
public LiveData<Question> getQuestionLiveData(int id) {
return questionRepository.getQuestionLiveData(id);
}
And then observing it in the View然后在视图中观察它
viewModel.getQuestionLiveData(packageId).observe(getViewLifecycleOwner(), new Observer<com.questionTest.practice.Model.Question>() {
@Override
public void onChanged(com.questionTest.practice.Model.QuestionQuestion question) {
Do stuff here////
}
}
});
The next part is where i'm not sure.下一部分是我不确定的地方。 i added this in the view model
我在视图模型中添加了这个
MutableLiveData mutableLiveData = new MutableLiveData();
and then tried to assign the this to the question然后尝试将 this 分配给问题
mutableLiveData = (MutableLivedata) getQuestionLiveData(id);
so i could use update the values but this throws an Casting error.所以我可以使用更新值,但这会引发 Casting 错误。
Im either missing something or i cannot do this so any help will be welcomed thanks我要么遗漏了什么,要么我不能这样做,所以欢迎任何帮助,谢谢
In this case, There is no need for MutableLiveData
.在这种情况下,不需要
MutableLiveData
。 MutableLiveData is LiveData
which publicly exposes setValue()
and postValue()
method. MutableLiveData是
LiveData
其公开揭露setValue()
和postValue()
方法。 So if you are not setting LiveData
values inside ViewModel class, there is no need for MutableLiveData
.因此,如果您不在 ViewModel 类中设置
LiveData
值,则不需要MutableLiveData
。 Here the Dao class generate LiveData
for you and you should observe
that LiveData
.这里 Dao 类为您生成
LiveData
,您应该observe
LiveData
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.