java 如何使用 RxJava 在 onNext() 中抛出错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40128235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I throw error in onNext() with RxJava
提问by Rox
.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();
}
}
);
I don't wanna handle (!response.isSuccess())
in onNext()
. How can I throw it to onError()
and handle with other throwable together?
我不想处理(!response.isSuccess())
在onNext()
。我怎样才能把它扔到onError()
并与其他可扔物一起处理?
回答by Tassos Bassoukos
If FailureException extends RuntimeException
, then
如果FailureException extends RuntimeException
,那么
.doOnNext(response -> {
if(!response.isSuccess())
throw new FailureException(response.getMessage());
})
.subscribe(
item -> { /* handle success */ },
error -> { /* handle failure */ }
);
This works best if you throw the exception as early as possible, as then you can do retries, alternative responses etc. easily.
如果您尽早抛出异常,这将最有效,因为这样您就可以轻松地进行重试、替代响应等。
回答by krp
you can flatMap
your response to Response or Error
您可以flatMap
对 Response 或 Error 做出回应
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()));
}
}
})
回答by R. Zagórski
The solution is to add an operator in the middle. My suggestion is to use map
as it does not generate new Observable
object (in comparison to flatMap
which does it):
解决方法是在中间添加一个操作符。我的建议是使用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()));
}
}
})