.subscribe(
new Action1<Response>() {
@Override
public void call(Response response) {
if (response.isSuccess())
//handle success
else
//throw an Throwable(reponse.getMessage())
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
//handle Throwable throw from onNext();
}
}
);
我不想在onNext()
中处理(!response.isSuccess())
。我怎么把它扔给onError()
和其他可扔物一起处理?
如果FailureException extends RuntimeException
,则
.doOnNext(response -> {
if(!response.isSuccess())
throw new FailureException(response.getMessage());
})
.subscribe(
item -> { /* handle success */ },
error -> { /* handle failure */ }
);
如果你尽可能早地抛出异常,这样做效果最好,因为这样你就可以很容易地进行重试,替代响应等。
您可以对响应或错误的响应进行flatMap
flatMap(new Func1<Response, Observable<Response>>() {
@Override
public Observable<Response> call(Response response) {
if(response.isSuccess()){
return Observable.just(response);
} else {
return Observable.error(new Throwable(response.getMessage()));
}
}
})
解决方案是在中间添加一个操作符。我的建议是使用map
,因为它不会生成新的Observable
对象(与flatMap
相比):
.map(new Func1<Response, Response>() {
@Override
public Response call(Response response) {
if (response.isSuccess()) {
return response;
} else {
throw new Throwable(reponse.getMessage()));
}
}
})