Apply retries in a RXjava

假装没事ソ 提交于 2019-12-19 08:20:13

问题


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(...)
                        )

        );
}

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)

Is there an option to implement it with RXJava methods?


回答1:


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(...)


来源:https://stackoverflow.com/questions/34740091/apply-retries-in-a-rxjava

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!