简体   繁体   中英

Change LiveData source by updating a variable

I want the LiveData source for a RecyclerView to change depending on which list you selected. And that if you've selected a source in this search. At the moment I can't switch back and forth between the sources. So I can display items from my Room database, but I can't change the source if I've selected another list.

Example: If you selected List 2, the LiveData source will be changed and all items contained in that List 2 will be displayed. Now you should also be able to search for words in this list 2. How can you do this during the runtime of an app?

A part of my current Repository :

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

And a part of my current ViewModel :

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

I do not see any setValue or getValue function that is being called on your LiveData actually.

In order to change the LiveData to interact with the live changes, you need to call the setValue in your LiveData object. Something like the following should fix your problem here I think.

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

And you do not have to return the LiveData object from the repository function anymore.

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

I hope that helps!

I want to share my personal opinion on implementing this actually. I would rather have a ContentObserver instead of a LiveData setup. Implementation with a ContentObserver and a CursorLoader looks like an easier and robust solution in my humble opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM