Best practice: Runtime filters with Room and LiveData

后端 未结 3 487
傲寒
傲寒 2021-02-02 11:24

I am working on a screen that shows the contents of a Room wrapped DB using a recycler. The adapter gets the LiveData from a ViewModel that hides the query call on the Room DAO

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 11:42

    I'm working in a similar problem. Initially I had RxJava but now I'm converting it to LiveData.

    This is how I'm doing inside my ViewModel:

    // Inside ViewModel
    MutableLiveData modelFilter = new MutableLiveData<>();
    LiveData> modelLiveData;
    

    This modelLivedata is constructed in the following way inside view model constructor:

            // In ViewModel constructor
            modelLiveData = Transformations.switchMap(modelFilter,
                        new android.arch.core.util.Function>>() {
                            @Override
                            public LiveData> apply(FilterState filterState) {
                                return modelRepository.getModelLiveData(getQueryFromFilter(filterState));
                            }
                        });
    

    When the view model receives another filter to be applied, it does:

    // In ViewModel. This method receives the filtering data and sets the modelFilter 
    // mutablelivedata with this new filter. This will be "transformed" in new modelLiveData value.
    public void filterModel(FilterState filterState) {
    
        modelFilter.postValue(filterState);
    }
    

    Then, this new filter will be "transformed" in a new livedata value which will be sent to the observer (a fragment).

    The fragment gets the livedata to observe through a call in the view model:

    // In ViewModel
    public LiveData> getModelLiveData() {
    
        return modelLiveData;
    
    }
    

    And inside my fragment I have:

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    
        ViewModel viewModel = ViewModelProviders.of(this.getActivity()).get(ViewModel.class);
    
        viewModel.getModelLiveData().observe(this.getViewLifecycleOwner(), new Observer>() {
            @Override
            public void onChanged(@Nullable PagedList model) {
                modelListViewAdapter.submitList(model);
            }
        });
    
    }
    

    I hope it helps.

提交回复
热议问题