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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:56:41  来源:igfitidea点击:

How can I throw error in onNext() with RxJava

javarx-java

提问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 flatMapyour 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 mapas it does not generate new Observableobject (in comparison to flatMapwhich 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()));
        }
    }
 })