java - 通过更新变量更改 LiveData 源
问题描述
我希望根据您选择的列表更改LiveData
a 的来源。RecyclerView
如果您在此搜索中选择了一个来源。目前我无法在源之间来回切换。因此,我可以显示 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);
}
解决方案
我没有看到您实际调用的任何函数setValue
或函数。getValue
LiveData
为了改变LiveData
以与实时更改交互,您需要setValue
在LiveData
对象中调用 。我认为像下面这样的东西应该可以解决你的问题。
// 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
设置。以我的拙见,用 aContentObserver
和 a实现看起来是一个更简单、更强大的解决方案。CursorLoader
推荐阅读
- python - 图像相似度的连体网络
- django - 如何知道用户点击注销后是否到达登录页面?姜戈
- javascript - 在 Popup 加载时从 Magnific Popup 的调用按钮访问属性
- c++ - Boost.Python 不是 .lib
- azure - 警告: foo 的数据已达到每日 0.0323 GB 的上限,并且您的应用遥测数据的收集将停止,直到 UTC 时间 2018 年 6 月 23 日上午 9:00
- java - 如何从源代码中获取使用 Gradle 构建的工件版本
- python-3.x - 如何保存和恢复 tf.estimator 模型
- android - SetScrollY 在片段中不起作用
- java - 在访问相机之前我需要按两次按钮
- python - 在整个 DataFrame 上应用函数的 Pandas 方法