我怎么能用RxJava在next()上抛出错误

2022-09-02 20:22:06
.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();
        }
    }
);

我不想处理.我怎样才能把它扔到一起,并与其他可扔的东西一起处理?(!response.isSuccess())onNext()onError()


答案 1

如果为 ,则FailureException extends RuntimeException

.doOnNext(response -> {
  if(!response.isSuccess())
    throw new FailureException(response.getMessage());
})
.subscribe(
    item  -> { /* handle success */ },
    error -> { /* handle failure */ }
);

如果您尽早抛出异常,则效果最好,因为这样您就可以轻松地进行重试,替代响应等。


答案 2

你可以你的回应响应或错误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()));
        }
    }
})

推荐