I implemented two repository in order to manage my data. So, if there are not data in database, it should ask to the API about it. I saw in other post that this could be resolved using switchIfEmpty, but it didn't work for me.
I tried the following code. The line restApiFlavorRepository.query(specification) is called, but the subscriber is never notified.
public Observable query(Specification specification) {
final Observable observable = flavorDaoRepository.query(specification);
return observable.map(new Func1() {
@Override
public Observable<List<Flavor>> call(Object o) {
if(((ArrayList<Flavor>)o).isEmpty()) {
return restApiFlavorRepository.query(specification);
}
return null;
}
});
}
and this
public Observable query(Specification specification) {
final Observable observable = flavorDaoRepository.query(specification);
return observable.switchIfEmpty(restApiFlavorRepository.query(specification));
}
And I'm still getting empty list, when I should obtain two Flavors.
UPDATED
What I was looking for, was this...
public Observable query(Specification specification) {
Observable<List<Plant>> query = mRepositories.get(0).query(specification);
List<Plant> list = new ArrayList<>();
query.subscribe(plants -> list.addAll(plants));
Observable<List<Plant>> observable = Observable.just(list);
return observable.map(v -> !v.isEmpty()).firstOrDefault(false)
.flatMap(exists -> exists
? observable
: mRepositories.get(1).query(null));
}
and it works like charm!! :)
The switchIfEmpty()
requires the source to complete without any values in order to switch to the second source:
Observable.empty().switchIfEmpty(Observable.just(1))
.subscribe(System.out::println);
This one won't switch:
Observable.just(new ArrayList<Integer>())
.switchIfEmpty(Observable.just(Arrays.asList(2)))
.subscribe(System.out::println);
If you want to switch on a 'custom' notion of emptiness, you can use filter
:
Observable.just(new ArrayList<Integer>())
.filter(v -> !v.isEmpty())
.switchIfEmpty(Observable.just(Arrays.asList(2)))
.subscribe(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With