I have an Observable that I want to terminate if a certain condition is not met (that is if the response from a certain website is unsuccessful), so that I can re-query the website, and call the observable again. How do I go about doing it?
Here's what I want to do:
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
//Perform network actions here
if (!response.isSuccessful()) {
//terminate this Observable so I can retrieve the token and call this observable again
}
}
});
You can use the retry operator of Rx. And need not to terminate an Observable.
Defined a custom exception:
public class FailedException extends RuntimeException{
// ...
}
private static final int RETRY_COUNT = 3; // max retry counts
Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
//Perform network actions here
if (!response.isSuccessful()) {
// if response is unsucceed, invoke onError method and it will be stop emit data and into retry method.
subscriber.onError(new FailedException());
}
}
})
.retry((integer, throwable) -> {
// Retry network actions when failed.
// if return true, Observable will be retry to network actions emit data;
// if return false, you can process in onError() method of Subscribe.
return throwable instanceof FailedException && integer < RETRY_COUNT;
})
You can filter the result before subscribing. Do not handle it when you create your observable.
Check observable.filter function