Reputation: 159
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
}
});
}
Upvotes: 3
Views: 1352
Reputation: 1232
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);
}
});
}
});
Upvotes: 5
Reputation: 5095
You can check the exception type as seen in the code below. The lambda inside flatMap
will be called for each error, where you can check the type via instanceof
. I haven't worked with RXJava in a while and didn't test if your return observable.delay(5, TimeUnit.SECONDS);
will still work fyi :)
public Observable<List<String>> getData() {
return apiConsumer.getData().retryWhen(errors -> errors.flatMap(error -> {
// This lambda will be called for each error. Check the type:
if (error instanceof IOException) {
return observable.delay(5, TimeUnit.SECONDS);
}
//Dont retry, pass the exception to onError
})
)
}
My answer is based on this tutorial, which provides more information about the topic.
Upvotes: 0