RxJava等待单个事件,RxJava

时间:2019-08-16 11:31:31

标签: java reactive-programming rx-java2 reactive

您如何等待带有timout的可观察值出现在单个值上?

我正在寻找类似的东西:

Observable<Acknowledgement> acknowledgementObservable;
port.send(new Message());
Optional<Acknowledgement> ack = acknowledgementObservable.getFirst(100, TimeUnit.MILLISECONDS);

2 个答案:

答案 0 :(得分:1)

首先,按照Converting between Completablefuture and Observable中所述将Observable转换为CompletableFuture

Observable<Acknowledgement> acknowledgementObservable;
port.send(new Message());
CompletableFuture<T> future = new CompletableFuture<>();
acknowledgementObservable
    .doOnError(future::completeExceptionally)
    .single()
    .forEach(future::complete);

然后,使用超时等待事件:

Acknowledgement ack = future.get(100, TimeUnit.MILLISECONDS);

如果发生超时,它将抛出TimeoutException

答案 1 :(得分:0)

您可以通过添加 .timeout() 和 .onErrorComplete() .blockingGet() 来实现

所以在这个例子中它会是:

    Acknowledgement ack = acknowledgementObservable
                              .firstElement()
                              .timeout(3, TimeUnit.SECONDS)
                              .onErrorComplete()
                              .blockingGet();

如果超时,ack将为空。