[英]Change LiveData source by updating a variable
我希望RecyclerView
的LiveData
源根據您選擇的列表進行更改。 如果您在此搜索中選擇了一個來源。 目前我無法在來源之間來回切換。 因此,我可以顯示 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
上調用了任何setValue
或getValue
函數。
為了更改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
設置。 以我的ContentObserver
,使用ContentObserver
和CursorLoader
看起來是一個更簡單、更強大的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.