我正在使用retrofit来返回一个observable,因为REST API调用服务器。通常会发生请求超时异常并且observable停止执行。如果异常属于特定类型,如何重新订阅重试
myObservable
.subscribe(new Subscriber<Something> sub(){
@override
void onNext(Something something){
//do something with something
}
@override
void onError(Throwable e){
//retry and resend call to server if e is request timeout exception
}
答案 0 :(得分:2)
您可以使用retry运算符。
示例:
myObservable
.retry((retryCount, throwable) -> retryCount < 3 && throwable instanceof SocketTimeoutException)
.subscribe(new Subscriber<Something> sub(){
@override
void onNext(Something something){
//do something with something
}
@override
void onError(Throwable e){
}
在示例中,当最多SocketTimeoutException
次3次时,它将重新订阅。
或没有lambda:
myObservable
.retry(new Func2<Integer, Throwable, Boolean>() {
@Override
public Boolean call(Integer retryCount, Throwable throwable) {
return retryCount < 3 && throwable instanceof SocketTimeoutException;
}
})
.subscribe(new Subscriber<Something> sub(){
@override
void onNext(Something something){
//do something with something
}
@override
void onError(Throwable e){
}