Liberty
Liberty

Reputation: 663

RxJava android Flowable retryWhen doesn't calling onError when occured error at last retry

my Flowable is returned from Retrofit ApiService, i attempt the below code to implement error retry mechanism, i wish it can call onError function when occurred error at last retry.

   flowable.retryWhen(throwableFlowable -> {
                AtomicInteger retryCounter = new AtomicInteger();
                return throwableFlowable
                    .takeWhile(throwable -> retryCounter.getAndIncrement() < 3);
            })
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(onNext, onError, onComplete, onSubscribe);

but it doesn't call the onError function when occurred error at last retry. I try add doOnError(onError) before retryWhen, but it doesn't work. Could anyone help me?

the RxJava is 2.2.19, the RxAndroid version is 2.1.1.

Upvotes: 0

Views: 395

Answers (1)

akarnokd
akarnokd

Reputation: 69997

You need to make the inner flow signal an onError. If you want this to be the last error from the main sequence, rethrow it in takeWhile:

.takeWhile(throwable -> {
  if (retryCounter.getAndIncrement() < 3) {
    return true;
  }
  throw throwable;
})

Edit: Alternatively, you could replace takeWhile with flatMap and signal a Flowable.error.

flowable.retryWhen(throwableFlowable -> {
    AtomicInteger retryCounter = new AtomicInteger();
    return throwableFlowable
           .flatMap(throwable -> {
               if (retryCounter.getAndIncrement() < 3) {
                   return Flowable.just(1);
               }
               return Flowable.<Integer>error(throwable);
           });
})

Upvotes: 1

Related Questions