I'm new to LiveData and I've been doing some tests lately. I have an app where I need to display data that can be filtered (name, category, date...). The filters can be combined too (name + date). This data comes from an API call with Retrofit + RXJava.
I know that I can have the data directly on my view without using LiveData. However, I thought that it would be interesting to use a ViewModel + LiveData. First, to test how it works but also to avoid trying to set data if the view is not active (thanks to LiveData) and save the data in case of configuration changes (thanks to ViewModel). These were things that I had to handle manually before.
So the problem is that I didn't find a way to easily handle the filters with LiveData. In cases where the user chooses one filter I managed to make it work with switchMap:
return Transformations.switchMap(filter,
filter -> LiveDataReactiveStreams.fromPublisher(
repository.getData(filter).toFlowable(BackpressureStrategy.BUFFER)));
If he chooses two filters, I saw that I could use a custom MediatorLiveData and that's what I did. However, the problem here is that my repository call is done as many times as the number of filters I have and I can't set two filters at the same time.
My custom MediatorLiveData:
class CustomLiveData extends MediatorLiveData<Filter> {
CustomLiveData(LiveData<String> name, LiveData<String> category) {
addSource(name, name -> {
setValue(new Filter(name, category.getValue()));
});
addSource(category, category -> {
setValue(new Filter(name.getValue(), newCategory));
});
}
}
CustomLiveData trigger = new CustomLiveData(name, category);
return Transformations.switchMap(trigger,
filter -> LiveDataReactiveStreams.fromPublisher(
repository.getData(filter.getName(), filter.getCategory())
.toFlowable(BackpressureStrategy.BUFFER)));
Did I understand well the usage of MediatorLiveData? Is it possible to do what I'm trying to achieve with LiveData?
Thanks!