You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何OnErrorNotImplementedException不会在onComplete和onNext中触发?

Why does RxJava2 throw OnErrorNotImplementedException only when onError is unimplemented, not onComplete or onNext?

Great question! Let’s break this down by looking at RxJava’s core design principles and how each of these subscriber methods is treated:

  • Errors are terminal, unhandled failures that demand attention
    RxJava adheres to the Reactive Streams specification, which defines errors as terminal, critical events. Once an error is emitted, the stream stops immediately—there’s no resuming after that. Unlike onNext (which can fire multiple times for regular emissions) or onComplete (a signal that the stream finished successfully), errors represent unexpected, potentially harmful failures that can’t be safely ignored. If you don’t provide an onError handler, RxJava has no way to resolve or report that failure, so it throws OnErrorNotImplementedException to force you to address this gap.

  • onComplete and onNext have safe, ignorable defaults
    The other subscriber methods don’t trigger exceptions when unimplemented because ignoring them is often an intentional, safe choice:

    • onNext: If you don’t implement it (for example, using a Completable that doesn’t emit items, or just choosing not to process emissions), RxJava simply discards the emitted values. There’s no inherent risk here—skipping items is a valid use case.
    • onComplete: This is a success signal. Not implementing it just means you don’t need to be notified when the stream finishes successfully, which is totally acceptable in many scenarios. RxJava doesn’t throw an exception here because ignoring completion doesn’t leave an unhandled failure state.
  • A quick code example to drive this home
    Let’s see the difference in action. First, an Observable that fails without an onError handler:

    Observable.just("hello")
      .map(s -> { throw new RuntimeException("Something broke!"); })
      .subscribe(); // No onError defined
    

    This will immediately throw OnErrorNotImplementedException—the error has nowhere to go, so RxJava alerts you. Now, an Observable that completes without onNext or onComplete:

    Observable.just("hello")
      .subscribe(); // No onNext/onComplete defined
    

    This runs perfectly fine. RxJava emits the item and completes silently, since there’s no handler to process those events—and that’s okay.

内容的提问来源于stack exchange,提问作者紫陽花

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:38:35