I'm new to RxJava 2 and want to retry a Completable server API call until success, while emitting notifications of the retry attempts so that my UI can display the retry status to the user.
Something like this:
public Observable<RetryAttempt> retryServerCall() {
// execute Completable serverCall()
// if an error is thrown, emit new RetryAttempt(++retryCount, error) to subscriber
// retry until serverCall() is successful
}
public Completable serverCall();
public class RetryAttempt {
public RetryAttempt(int retryCount, Throwable cause);
}
I've tried a few different approaches and ran into roadblocks. The closest is this approach, creating an enclosing Observable and explicitly calling onNext() / onComplete() / onError().
public Observable<RetryAttempt> retryServerCall() {
final int[] retryCount = {0};
return Observable.create(e ->
serverCall()
.doOnError(throwable -> e.onNext(new RequestHelp.RetryAttempt(++retryCount[0], throwable)))
.retry()
.subscribe(() -> e.onComplete(), throwable -> e.onError(throwable)));
}
Perhaps its a somewhat a peripheral matter, but I had to use the final array for retryCount in order to avoid the error variable used in lambda should be final or effectively final.
I know there must be a better to accomplish this using Rx voodoo. Any guidance is much appreciated!
subscribeWithto get aDisposablefor the innerObservable, and then dispose viasetDisposable, correct? - HolySamosa