Retry a call with Retrofit 2 and RxJava2 after displaying a dialog

前端 未结 2 882
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 17:32

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

2条回答
  •  迷失自我
    2021-02-04 17:55

    final PublishSubject 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:

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

    提交回复
    热议问题