简体   繁体   English

如何使用RxJava在onNext()中抛出错误

[英]How can I throw error in onNext() with RxJava

.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() . 我不想在onNext()处理(!response.isSuccess()) onNext() How can I throw it to onError() and handle with other throwable together? 我如何将它抛给onError()并与其他throwable一起处理?

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. 如果您尽早抛出异常,这种方法效果最好,因为您可以轻松地进行重试,替代响应等。

you can flatMap your response to Response or Error 你可以将你的响应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()));
        }
    }
})

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()));
        }
    }
 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM