retrofitrx-javarx-android

RxJava retry based on logic


Here is the case, I have an API call using Retrofit that might fail due to a network error. If it fails we will show an error message with a retry button. When the 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 an 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 an Observable error then it will stop. Same issue here, I need to not start the retry process unless the user 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.

Are there any other solutions to go with?


Solution

  • 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