为什么不在`onComplete`和`onNext`中出现`OnErrorNotImplementedException`?

问题描述 投票:0回答:1

当我学习RxJava2时,我遇到了OnErrorNotImplementedException。我了解到这种异常的发生是由于没有为订阅者实现错误处理程序。所以,我想为什么不存在除了onError方法。为什么?

java rx-java2
1个回答
0
投票

doOnError方法不消耗错误,最终它将被抛入订阅者。在这种情况下,如果您没有处理订阅者,那么OnErrorNotImplementedException将被抛出。

以下方法将消耗subscribe方法中提到的错误。

方法1:

Observable.just(new Object())
            .doOnNext(o -> { /* /* This method catches the on next but doesn't consume it. */})
            .doOnComplete(() -> { /* test */})
            .doOnError(throwable -> {/* This method catches the error but doesn't consume it. */})
            .subscribe(o ->
                    {/* success */}
                    ,
                    throwable -> {/* error */} // here error will be consumed at the end
            );

方法2:

Observable.just(new Object())
            .doOnNext(o -> { /* /* This method catches the on next but doesn't consume it. */})
            .doOnComplete(() -> { /* test */})
            .doOnError(throwable -> {/* This method catches the error but doesn't consume it. */})
            .subscribe(
                    new DefaultObserver<Object>() {
                        @Override
                        public void onNext(Object o) {

                        }

                        @Override
                        public void onError(Throwable e) {
                          // here error will be consumed at the end
                        }

                        @Override
                        public void onComplete() {

                        }
                    }
            );

总的来说,你必须消耗错误,否则你将面临你提到的同样的错误。

© www.soinside.com 2019 - 2024. All rights reserved.