1

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")
                    }
            )

And the result is shwon as below.

Debug: retryWhen proceed...

Debug: error : There is a exception

The question is that when retryWhen operator is triggered?

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!

Community
  • 1
  • 1
Berry Huang
  • 23
  • 1
  • 4

1 Answers1

3

retryWhen { errors -> ... } take an Observable<Throwable> and should return an Observable that return anything for retrying or an error for stop retrying.

One example could be:

.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);
  });
})

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

Documentation:
* Great blog article that explained the retryWhen

Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57
  • Thanks for your reply, but my major question is that Flowable.just(1, 2, 3, 4, 5) do not emit any error to my observer, so I assume retryWhen operator would not be triiger. But thre behavior show me that retryWhen operator has be triggered. How did this happened ? – Berry Huang Nov 02 '18 at 09:11
  • The lambda [executes before](https://github.com/ReactiveX/RxJava/blob/2.x/src/main/java/io/reactivex/internal/operators/flowable/FlowableRetryWhen.java#L45) any subscription to `just` and you just crash the lambda. Do not crash the lambda. – akarnokd Nov 02 '18 at 09:57
  • @akarnokd Thank you for you for your reply! After studying source code I totally understand what's going on! – Berry Huang Nov 03 '18 at 07:27