首页 > 解决方案 > 通过更新变量更改 LiveData 源

问题描述

我希望根据您选择的列表更改LiveDataa 的来源。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);
}

标签: javaandroidandroid-roomandroid-databindingandroid-livedata

解决方案


我没有看到您实际调用的任何函数setValue或函数。getValueLiveData

为了改变LiveData以与实时更改交互,您需要setValueLiveData对象中调用 。我认为像下面这样的东西应该可以解决你的问题。

// 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


推荐阅读