当我学习RxJava2时,我遇到了OnErrorNotImplementedException
。我了解到这种异常的发生是由于没有为订阅者实现错误处理程序。所以,我想为什么不存在除了onError
方法。为什么?
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() {
}
}
);
总的来说,你必须消耗错误,否则你将面临你提到的同样的错误。