【发布时间】:2016-08-05 05:44:22
【问题描述】:
我希望我的代码重复某个异步操作,直到此操作成功(即,直到它返回 true)。
目前我正在使用以下解决方法:
Supplier<Observable<Boolean>> myOperation = () -> {
// do something useful and return 'true' if it was successful
// NOTE: GENERATING A RANDOM NUMBER IS JUST AN EXAMPLE HERE
// I WANT TO RUN AN ASYNCHRONOUS OPERATION (LIKE PINGING A SERVER
// OR THE LIKE) AND RETRY IT UNTIL IT SUCCEEDS.
System.out.println("Try");
return Observable.just(Math.random() > 0.9);
};
final Throwable retry = new IllegalStateException();
Observable.<Boolean>create(subscriber -> {
myOperation.get().subscribe(subscriber);
}).flatMap(b -> b ? Observable.just(b) : Observable.error(retry))
.retryWhen(exceptions -> exceptions.flatMap(exception -> {
if (exception == retry) {
return Observable.timer(1, TimeUnit.SECONDS);
}
return Observable.error(exception);
}))
.toBlocking()
.forEach(b -> {
System.out.println("Connected.");
});
它运行良好并打印出如下内容:
Try
Try
...
Try
Connected.
代码做我想要的,但它看起来不是很优雅。我相信一定有更好的方法。也许通过使用自定义Operator?
有没有人知道如何在 RxJava 中实现相同的功能,但以更易读的方式,并且没有人工的 Throwable?
【问题讨论】: