问题描述
我正在尝试深入了解 retryWhen 运算符,我有一些代码如下.
I'm trying to understand retryWhen operator in depth and I have some code as below.
Flowable.just(1, 2, 3, 4, 5)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.retryWhen { throwable ->
Log.d("Debug", "retryWhen proceed...")
throw Exception("There is a exception")
}
.subscribe(
{ item ->
Log.d("Debug", "success : $item")
},
{ throwable ->
Log.d("Debug", "error : ${throwable.message}")
},
{
Log.d("Debug", "complete")
}
)
结果如下所示.
调试:重试继续时...
调试:错误:有异常
问题是什么时候触发retryWhen操作符?
The question is that when retryWhen operator is triggered?
我假设只有在发生异常时才会触发 retryWhen 操作符.
I assume retryWhen operator will be triggered only when there is a exception occurs.
但结果显然不是我想的那样,
But the result is not what I thought obviously,
对此有什么想法吗?谢谢!
Any thoughts on this? Thanks!
推荐答案
retryWhen { errors ->... }
接受一个 Observable
并且应该返回一个 Observable
返回任何重试或错误em>停止重试.
retryWhen { errors -> ... }
take an Observable<Throwable>
and should return an Observable
that return anything for retrying or an error for stop retrying.
一个例子可能是:
.retryWhen(attempts -> {
return attempts.zipWith(Observable.range(1, 3), (n, i) -> i).flatMap(i -> {
System.out.println("delay retry by " + i + " second(s)");
return Observable.timer(i, TimeUnit.SECONDS);
});
})
(取自 http://reactivex.io/documentation/operators/retry.html)
此代码将延迟每次重试.
(taken from http://reactivex.io/documentation/operators/retry.html)
This code will delay each retry.
顺便说一句,抛出异常不是这个方法要做的事情.
By the way, throwing an exception is not the thing to do in this method.
文档:
* 很棒的博客文章,解释了retryWhen
这篇关于RxJava 的 retryWhen 操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!