aatish rana aatish rana - 9 months ago 31
Android Question

exception type in Observable.retrywhen

i am new to rxJava, this is probably very stupid question but i am not able to figure out how to find the type of exception in retry when.
i want to retry on a particular exception (eg Io Exception), but on others
i want to pass the exception down the chain.

public Observable<List<String>> getData()
{
return apiConsumer.getData()
.retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>()
{
@Override
public Observable<?> call(Observable<? extends Throwable> observable)
{
// if(exception type == io exception)
return observable.delay(5, TimeUnit.SECONDS);
//else
// dont retry, pass the exception to onError
}
});
}

Answer Source

Try the following code:

return apiConsumer.getData().retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {
    @Override
    public Observable<?> call(Observable<? extends Throwable> observable) {
        return observable.flatMap(new Func1<Throwable, Observable<?>>() {
            @Override public Observable<?> call(Throwable throwable) {
                if(throwable instanceof IOException) {
                   // Retry code
                   // For example: retry after 5seconds
                   return Observable.timer(5, TimeUnit.SECONDS);
                }
                // Pass the throwable
                return Observable.error(throwable);
            }
        });
    }
});