Android Room LiveData select query parameters

前端 未结 1 856
抹茶落季
抹茶落季 2020-12-08 08:31

I decided to teach myself Java and Android by doing a simple database app. I already implemented some functionality the \"lazy\" way - all selects are done on the main threa

相关标签:
1条回答
  • 2020-12-08 09:20

    I think your solution is a Transformations.switchMap. The simplest example how it may works in the case from codelab

    public class WordViewModel extends AndroidViewModel {
        private WordRepository mRepository;
        private LiveData<List<Word>> mAllWords;
        private LiveData<List<Word>> searchByLiveData;
        private MutableLiveData<String> filterLiveData = new MutableLiveData<>();
    
        public WordViewModel (Application application) {
            super(application);
            mRepository = new WordRepository(application);
            mAllWords = mRepository.getAllWords();
            searchByLiveData = Transformations.switchMap(filterLiveData, 
                                                         v -> mRepository.searchBy(v));
        }
    
        LiveData<List<Word>> getSearchBy() { return searchByLiveData; }
        void setFilter(String filter) { filterLiveData.setValue(filter); }
        LiveData<List<Word>> getAllWords() { return mAllWords; }
        public void insert(Word word) { mRepository.insert(word); }
    }
    

    So, when you set filter value, it will change value of searchByLiveData

    I hope this helps you.

    0 讨论(0)
提交回复
热议问题