-->

RxJava retry based on logic

2019-04-07 12:15发布

问题:

Here is the case, I have API call usign Retrofit that might fail due to network error. If it fails we will show error message with a retry button. When user presses the retry button we need to retry the latest Observable again.

Possible Solutions:

  1. Retry: Retry should be used before subscribing to the observable and it will immediately resubscribe again if error happens and that is what I don't want, I need to resubscribe only if the user pressed the Retry button.

  2. RetryWhen: It Will keep trying as you emit items until you emit Observable error then it will stop. Same issue here, I need to not start the retry process unless the use decides to.

  3. Resubscribe to the same Observable: This solution will start emitting the Observable items, the problem with this is that we are using the cache operator, so if one Observable failed, we got the failed item cached and when we do subscribe again, we got the same error again.

Is there any other solutions to go with?

回答1:

You can go with retryWhen, which parameter - Func1 - returns an Observable which indicates when a retry should happen. For example :

PublishSubject<Object> retryButtonClicked = PublishSubject.create();

Observable
        .error(new RuntimeException())
        .doOnError(throwable -> System.out.println("error"))
        .retryWhen(observable -> observable.zipWith(retryButtonClicked, (o, o2) -> o))
        .subscribe();

retryButtonClicked.onNext(new Object());

every time retryButtonClicked emmits an event, Observable will be retried

Here's also an example - https://gist.github.com/benjchristensen/3363d420607f03307dd0