【发布时间】:2017-02-24 17:59:36
【问题描述】:
我是 RxJava 2 的新手,想重试 Completable 服务器 API 调用直到成功,同时发出重试尝试通知,以便我的 UI 可以向用户显示重试状态。
类似这样的:
public Observable<RetryAttempt> retryServerCall() {
// execute Completable serverCall()
// if an error is thrown, emit new RetryAttempt(++retryCount, error) to subscriber
// retry until serverCall() is successful
}
public Completable serverCall();
public class RetryAttempt {
public RetryAttempt(int retryCount, Throwable cause);
}
我尝试了几种不同的方法,但遇到了障碍。最接近的是这种方法,创建一个封闭的 Observable 并显式调用 onNext() / onComplete() / onError()。
public Observable<RetryAttempt> retryServerCall() {
final int[] retryCount = {0};
return Observable.create(e ->
serverCall()
.doOnError(throwable -> e.onNext(new RequestHelp.RetryAttempt(++retryCount[0], throwable)))
.retry()
.subscribe(() -> e.onComplete(), throwable -> e.onError(throwable)));
}
也许这是一个无关紧要的问题,但我不得不为retryCount 使用final 数组以避免出现variable used in lambda should be final or effectively final 错误。
我知道使用 Rx voodoo 必须有更好的方法来完成此任务。非常感谢任何指导!
【问题讨论】:
-
你不想完全像这样做,因为你会失去取消订阅的信号。
-
@Tassos 是的。我可以使用
subscribeWith为内部Observable获取Disposable,然后通过setDisposable处理,对吗?