MediatorLiveData or switchMap transformation with multiple parameters

前端 未结 4 1197
我在风中等你
我在风中等你 2020-12-13 00:23

I am using Transformations.switchMap in my ViewModel so my LiveData collection, observed in my fragment, reacts on changes of code parameter.

4条回答
  •  悲&欢浪女
    2020-12-13 00:45

    Custom MediatorLiveData as proposed by @jL4 works great and is probably the solution.

    I just wanted to share the simplest solution that I think is to use an inner class to represent the composed filter values :

    public class MyViewModel extends AndroidViewModel {
    
        private final LiveData dayPrices;
        private final DBManager dbManager;
        private final MutableLiveData dayPriceFilter;
    
        public MyViewModel(Application application) {
            super(application);
            dbManager = new DBManager(application.getApplicationContext());
            dayPriceFilter = new MutableLiveData<>();
            dayPrices = Transformations.switchMap(dayPriceFilter, input -> dbManager.getDayPriceData(input.code, input.nbDays));
        }
    
        public LiveData getDayPrices() {
            return dayPrices;
        }
    
        public void setDayPriceFilter(String code, int nbDays) {
            DayPriceFilter update = new DayPriceFilter(code, nbDays);
            if (Objects.equals(dayPriceFilter.getValue(), update)) {
                return;
            }
            dayPriceFilter.setValue(update);
        }
    
        static class DayPriceFilter {
            final String code;
            final int nbDays;
    
            DayPriceFilter(String code, int nbDays) {
                this.code = code == null ? null : code.trim();
                this.nbDays = nbDays;
            }
        }
    
    }
    

    Then in the activity/fragment :

    public class MyFragment extends Fragment {
    
        private MyViewModel myViewModel;
    
        myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        myViewModel.setDayPriceFilter("SO", 365);
        myViewModel.getDayPrices().observe(MyFragment.this, dataList -> {
            // update UI with data from dataList
        });
    }
    

提交回复
热议问题