switchIfEmpty无法按预期工作

时间:2016-07-29 17:03:48

标签: java rx-java reactive-programming observable

我有两个可观察的执行。

我想只在第一个为空/空时以及在完成执行最终代码块时才执行第二个。

但是 - 即使第一个observable不为空,第二个observable也会一直执行。

  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);
    }

如您所见,handleLocation永远不会返回null / empty对象。

为什么addLocation(msg)被触发?

addLocation签名:

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

}

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

我设法通过将observable.fromCallable(()添加到addLocation来修复此问题。任何想法为什么以这种方式解决?

1 个答案:

答案 0 :(得分:0)

使用过滤器将发出通过过滤器的所有值。如果我理解正确,你正在寻找类似的东西:

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

这将发出第一个非空“结果”。