简体   繁体   中英

switchIfEmpty doesnt work as expected

I have two observable executions.

I want to execute the second only if first one is empty/null and when finish to execute the final code block.

However - the second observable always executed even if first observable is not empty.

  handleLocation(msg).filter(result -> result != null).switchIfEmpty(addLocation(msg)).subscribe(
                    response -> {
                        handleResponse(routingContext, transactionId, msg, response);
                    });


  private Observable<LocationDTO> handleLocation(JsonObject msg) {
      Location locationDTO=new locationDTO(); 
        ...
        return Observable.just(locationDTO);
    }

as you see handleLocation will never return null/empty object.

why addLocation(msg) getting triggered?

addLocation signature:

  private Observable<MyDTO> addLocation(JsonObject msg) {
    return redisRepo.getLocationByIp(ip).switchIfEmpty(getLocationByHost(host);

}

 private Observable<LocationDTO> getLocationByHost(Strin host) {
       ...
        return Observable.just(new LocationDTO());

I managed to fix this by adding return Observable.fromCallable(() to addLocation. any idea why it resolved this way?

Using filter will emit all the values that pass the filter. If I understand right, you are looking for something like:

    Observable.concat(cache, remote)
            .first(new Func1<Result, Boolean>() {
                @Override
                public Boolean call(Result result) {
                    return result != null;
                }
            });

This will emit the first non-null "Result".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM