7

I'm calling an API using Retrofit 2 and RxJava2. If a call fails, in some cases (e.g. no Internet connection), I want to display an error dialog to the user and let him retry.

As I'm using RxJava, I was thinking of using .retryWhen(...) but I don't know how to do that as it needs to wait for the user to press the button on the dialog.

At the moment I display the dialog but it retries before the user presses any button. Plus I would like the call to not be retried when the user presses 'cancel'.

Here is the code I have at the moment:

private void displayDialog(DialogInterface.OnClickListener positive, DialogInterface.OnClickListener negative) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Unexpected error, do you want to retry?")
            .setPositiveButton("Retry", positive)
            .setNegativeButton("Cancel", negative)
            .show();
}

private Observable<Boolean> notifyUser() {
    final PublishSubject<Boolean> subject = PublishSubject.create();
    displayDialog(
            (dialogInterface, i) -> subject.onNext(true),
            (dialogInterface, i) -> subject.onNext(false)
    );

    return subject;
}

private void onClick() {
    Log.d(TAG, "onClick");
    getData()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .retryWhen(attempts -> {
                return attempts.zipWith(
                        notifyUser(),
                        (throwable, res) -> res);
            })
            .subscribe(
                    s -> {
                        Log.d(TAG, "success");
                    });
}
Eselfar
  • 3,759
  • 3
  • 23
  • 43
  • I recently answered to a similar question: https://stackoverflow.com/a/47631107/1584654 – GVillani82 Dec 06 '17 at 10:50
  • @GVillani82 I've tried you example and I have some questions.#1 What happen if the Publisher never emit? We'll have a pending retry forever? #2 What should I do if I want to retry only on a specific Exception but not on the other ones? #3 If `retryWhen` is defined, no error error is ever emitted? – Eselfar Dec 06 '17 at 13:42
  • There were some mistakes actually in my previous example. Anyway I rewrite the answer and I tried to answer your questions. – GVillani82 Dec 06 '17 at 15:01

2 Answers2

10
final PublishSubject<Object> retrySubject = PublishSubject.create();

disposable.add(getData()
    .doOnError(throwable -> enableButton())
    .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
    .subscribeWith(/* do what you want with the result*/)
}));

When button is clicked you trigger this event:

retrySubject.onNext(new Object());

As you can see in this Marble diagram:

enter image description here

the error is not propagated. The retryWhen operator will indeed handle it and do a proper action. This is the reason why you have to enable (or for example show a Dialog) in doOnError, before retryWhen operator.

When you don't want to listen anymore for successive retry attempts, you just need to unsubscribe:

disposable.dispose();

As per your question:

What should I do if I want to retry only on a specific Exception but not on the other ones?

You can modify your retryWhen in this way:

.retryWhen(throwableObservable -> throwableObservable.flatMap(throwable -> {
      if (throwable instanceof TargetException) {
          return Observable.just(throwable).zipWith(retrySubject, (o, o2) -> o);
      } else {
          throw Throwables.propagate(throwable);
      }
}))

Where Throwables.propagate(throwable) is a Guava util that can be replaced with throw new RuntimeException(throwable);

GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • 2
    I am using Kotlin `.retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))` caused compile error (could be my fault of not understanding the lambda syntax), but I got it working with this simpler code: `.retryWhen{ retrySubject.toFlowable(BackpressureStrategy.LATEST) }` – Damn Vegetables Apr 29 '18 at 18:10
  • 1
    @Gvillani82 Is it possible to achieve this with a Single or Completable instead of Observable? – GuilhE May 10 '18 at 17:13
  • @GuilhE Yes, I've done this. You can use `retryWhen` for Single. – Vadim Kotov Aug 15 '19 at 15:10
  • 1
    @DamnVegetables this way you're ignoring `Flowable` of errors. If you would like to use it somehow, use this: `retryWhen { retryHandler -> retryHandler.zipWith(retrySubject.toFlowable(BackpressureStrategy.LATEST), BiFunction { t1, t2 -> t2 } ) }`. This is an example for retrying `Single`. – Vadim Kotov Aug 15 '19 at 15:14
0

for me i am using clean architecture and it was hard to put android code to show dialog in usecase or repository. so since i was using kotlin i passed in a lamba to take care of things for me. something like this:

here is my full presenter:

 class WeatherDetailsPresenter @Inject constructor(var getCurrentWeatherWithForecastUsecase: GetCurrentWithForcastedWeatherUsecase) : BaseMvpPresenter<WeatherDetailsView>() {

    fun presentCurrentAndForcastedWeather(country: String?) {
        getCurrentWeatherWithForecastUsecase.takeUnless { country?.isBlank() == true }?.apply {
            this.countyName = country
            execute(object : DefaultSubscriber<Pair<CurrentWeatherModel, ForecastedWeatherModel>>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading(true)
                }

                override fun onNext(t: Pair<CurrentWeatherModel, ForecastedWeatherModel>) {
                    super.onNext(t)
                    view?.showCurrentWeather(t.first)
                    view?.showForcastWeather(t.second)
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
//if i get an error pass in lambda to the dialog
                    myErrorDialog.setretryAction( {this@WeatherDetailsPresenter.presentCurrentAndForcastedWeather(country)})
                }

                override fun onComplete() {
                    super.onComplete()
                    showLoading(false)
                }
            })
        } ?: run { view?.showCountryUnavailable() }
    }

then in then errordialog i do this assuming its a dialogfragment:

lateinit var retryAction: () -> Unit

override fun onStart() {
        super.onStart()
        dialog.window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        button.setOnClickListener { dismiss();retryAction() }
    }

my code for on error is not acutally like that but just to give you an idea on how to pass in a lambda. im sure you can pass in a function of your own. in this case the lambda was the method itself to retry.

j2emanue
  • 60,549
  • 65
  • 286
  • 456