Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply retries in a 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(...)
                        )

        );
}

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?

like image 901
Bick Avatar asked Feb 09 '23 01:02

Bick


1 Answers

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(...)
like image 108
akarnokd Avatar answered Feb 12 '23 01:02

akarnokd