问题描述
我想运行一个使用RXJava重试的方法
I want to run a method with retries using RXJava
return Observable
.just(myObj)
.flatMap(doc ->
myFunc(myObj, ....)
)
.doOnError(e -> log.Error())
.onErrorResumeNext(myObj2 ->
methodIWantToRunWithRetries(...)
.onErrorResumeNext(myObj3 ->
methodIWantToRunWithRetries(...)
)
);
}
如果我使用 onErrorResumeNext
我需要多次嵌套我想要重试。
(除非我想用try / catch包围它)
If I use onErrorResumeNext
I need to nest it as many times I want my retries.
(unless I want to surround it with try/catch)
是否有使用RXJava方法实现它的选项?
Is there an option to implement it with RXJava methods?
推荐答案
RxJava提供标准的重试运算符,让您重试多次,重试如果异常匹配谓词或具有一些复杂的重试逻辑。前两个使用是最简单的:
RxJava offers standard retry operators that let you retry a number of times, retry if the exception matches a predicate or have some complicated retry logic. The first two use are the simplest:
source.retry(5).subscribe(...)
source.retry(e -> e instanceof IOException).subscribe(...);
后者要求组装一个二级观察者,现在可以附加延迟,计数器等:
The latter one requires assembling a secondary observable which now can have delays, counters, etc. attached:
source.retryWhen(o -> o.delay(100, TimeUnit.MILLISECONDS)).subscribe(...)
这篇关于在RXjava中应用重试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!