Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch observable if it is empty

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!! :)

like image 760
Ignacio Giagante Avatar asked May 31 '16 12:05

Ignacio Giagante


1 Answers

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);
like image 137
akarnokd Avatar answered Oct 13 '22 03:10

akarnokd