gpt4 book ai didi

java - 通过更新变量更改 LiveData 源

转载 作者:行者123 更新时间:2023-11-29 02:17:39 25 4
gpt4 key购买 nike

我希望 RecyclerViewLiveData 源根据您选择的列表进行更改。如果您在此搜索中选择了一个来源。目前我无法在来源之间来回切换。因此,我可以显示我的 Room 数据库中的项目,但如果我选择了另一个列表,则无法更改源。

示例:如果您选择列表 2,LiveData 源将更改,并且将显示该列表 2 中包含的所有项目。现在您应该还可以在此列表中搜索单词 2. 如何在应用程序运行时执行此操作?

我当前的 Repository 的一部分:

public LiveData<List<VocabularyEntity>> getVocabularies(int listNumber, String searchText) {
if (listNumber == 0) {
return listDao.getVocabularies(searchText);
} else {
return listDao.getVocabularyList(listNumber, searchText);
}
}

还有我当前的 ViewModel 的一部分:

public LiveData<List<ListEntity>> getLists() {
return repository.getLists(listNumber, searchText);
}

最佳答案

我实际上没有看到在您的 LiveData 上调用的任何 setValuegetValue 函数。

为了更改 LiveData 以与实时更改交互,您需要在 LiveData 对象中调用 setValue。我认为下面的内容应该可以解决您的问题。

// I am assuming you have this variable declared in your viewmodel
private LiveData<List<ListEntity>> vocabList;

public LiveData<List<ListEntity>> getLists() {
List<ListEntity> vocabListFromDB = repository.getLists(listNumber, searchText);
vocabList.setValue(vocabListFromDB);

return vocabList;
}

而且您不必再从存储库函数返回 LiveData 对象。

public List<VocabularyEntity> getVocabularies(int listNumber, String searchText) {
if(listNumber == 0) {
return listDao.getVocabularies(searchText);
} else {
return listDao.getVocabularyList(listNumber, searchText);
}
}

希望对您有所帮助!

我想分享我个人对实际实现的看法。我宁愿使用 ContentObserver 而不是 LiveData 设置。在我看来,使用 ContentObserverCursorLoader 实现看起来是一种更简单、更可靠的解决方案。

关于java - 通过更新变量更改 LiveData 源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59346709/

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