如何从阻止vertx future到RxJava Observable

时间:2017-09-20 11:17:23

标签: rx-java future blocking vert.x

我在回购邮件中看到了这样的代码。

   public Observable<Optional<DeviceInfo>> getDeviceInfo(final String userAgent) {
        final ObservableFuture<Optional<DeviceInfo>> observable = RxHelper.observableFuture();
        vertx.executeBlocking(future -> {
            try {
                final Optional<Device> device = Optional.ofNullable(engine.get().getDeviceForRequest(userAgent));
                if (device.isPresent()) {
                    future.complete(Optional.of(new DeviceInfo()));
                } else {
                    future.complete(Optional.empty());
                }
            } catch (final RuntimeException e) {
                LOGGER.error("Unable to get the UA device info {}, reason {}", userAgent, e.getMessage());
                future.fail(e.getMessage());
            }
        }, observable.toHandler());

        return observable.single();
    }

对我来说,编写那么多代码来执行这个阻塞代码并将未来映射到单个Observable似乎有点奇怪。

难道没有更简单,更好的方法来做到这一点吗?例如一些便利工厂方法等

1 个答案:

答案 0 :(得分:2)

使用Vert.x API for RxJavaOptional.map

public Single<Optional<DeviceInfo>> getDeviceInfo(final String userAgent) {
  return vertx.rxExecuteBlocking(future -> {
    try {
      final Optional<Device> device = Optional.ofNullable(engine.get().getDeviceForRequest(userAgent));
      future.complete(device.map(d -> new DeviceInfo()));
    } catch (final RuntimeException e) {
      LOGGER.error("Unable to get the UA device info {}, reason {}", userAgent, e.getMessage());
      future.fail(e.getMessage());
    }
  });
}