Logical RxJava Repeat

So, I have a call usign Retrofit API, which may fail due to a network error. If this fails, we will display an error message with a redo button. When the user clicks the repeat button, we need to repeat the last Observed again.

Possible solutions:

  • Try again: try again before subscribing to an observable, and it will immediately resend the subscription again if an error occurs, and this is what I do not want, I need to cancel the subscription only if the user clicked the retry button.

  • RetryWhen: it will keep trying when you emit items until you throw an Observable error, after which it stops. The same problem here, I do not need to start the repetition process, unless I decide to use it.

  • Resubscribe is also Observable: this solution will start emitting Observable elements, the problem is that we use the cache operator, so if one Observable failed, we got an invalid element, cached and when we do subscribe again, we got the same again a mistake.

Are there any other solutions?

+6
source share
1 answer

You can go with retryWhen, which parameter - Func1 - returns an Observable that indicates when the retry will occur. For instance:

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 allows an event, the Observable will be re-checked

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

+6
source

Source: https://habr.com/ru/post/989118/


All Articles