Why can an Android app using RxJava 3 crash with UndeliverableException after a screen is closed, and how do you handle it?
answer
- an error with nobody listening
- after dispose or after termination
- routed to a global hook
- RxJavaPlugins.setErrorHandler
- unwrap the cause, keep real bugs loud
basics
~20 sA late error from a disposed or already-terminated subscription has no observer, so RxJava wraps it in UndeliverableException and calls RxJavaPlugins.onError, which by default crashes an Android app. Install RxJavaPlugins.setErrorHandler in the Application to triage such errors.
solid answer
~40 sRxJava never swallows an error. When a source fails after its observer has disposed, typically a blocking call on `Schedulers.io()` that throws an `IOException` or `InterruptedException` because disposal interrupted its thread, or after the sequence has already terminated, the error cannot be delivered. RxJava routes it to `RxJavaPlugins.onError`, wrapping it in `UndeliverableException` unless it looks like a bug (`NullPointerException`, `IllegalArgumentException`, `IllegalStateException`, `MissingBackpressureException` or `OnErrorNotImplementedException`, for example). With no handler installed, that prints the stack trace and calls the current thread's uncaught exception handler, which on Android terminates the process. The fix is an app-level `RxJavaPlugins.setErrorHandler` in `Application.onCreate()` that unwraps the cause, ignores expected cancellation noise, and forwards likely bugs to the crash path. In your own `create` sources, call `emitter.tryOnError` so a disposed emitter does not produce one.
code
kotlin · 25 linesimport android.app.Application
import android.util.Log
import io.reactivex.rxjava3.exceptions.UndeliverableException
import io.reactivex.rxjava3.plugins.RxJavaPlugins
import java.io.IOException
class App : Application() {
override fun onCreate() {
super.onCreate()
RxJavaPlugins.setErrorHandler { error ->
val cause = if (error is UndeliverableException) error.cause ?: error else error
when (cause) {
is IOException, is InterruptedException -> {
// Expected after dispose: a cancelled call or an interrupted wait.
Log.w("Rx", "Undeliverable error ignored", cause)
}
else -> {
// Likely a bug: crash the way an uncaught exception would.
val thread = Thread.currentThread()
thread.uncaughtExceptionHandler?.uncaughtException(thread, cause)
}
}
}
}
}go deeper
Know that RxJava never silently drops an error, and that an error arriving after disposal goes to a global hook that can crash an Android app.
Explain how UndeliverableException wraps the cause, which error types pass through unwrapped, and what the default hook does with them on Android.
Trace a crash back to the source that failed late, fix it with tryOnError or cleaner cancellation, and install a triaging handler instead of a silent one.
Own the app-wide policy: which late errors are noise and which must crash or be reported, how the handler is tested, and why library modules leave it alone.
## The rule: no error is swallowed RxJava 2 introduced a design rule that RxJava 3 keeps: **no `Throwable` may be silently dropped**. The Reactive Streams protocol, however, forbids delivering a signal to an observer that has disposed its subscription or already received `onError` or `onComplete`. When an error meets one of those closed doors, it is an **undeliverable error**, and RxJava sends it to a global hook instead: `RxJavaPlugins.onError`. ## How an error becomes undeliverable The usual Android paths are all about timing: - **Disposal interrupts blocking work.** A screen closes, its `CompositeDisposable` is cleared, and a `Single.fromCallable` running a blocking network or disk call on `Schedulers.io()` is disposed. Disposal interrupts the worker thread; the blocking call throws an `InterruptedIOException`, another `IOException`, or an `InterruptedException`, and nobody is subscribed any more. - **Two parallel failures.** In `zip` or `merge`, the first failing source terminates the chain and disposes the others. If a second source fails at about the same time, its error arrives after termination. - **Hand-written emitters.** Code inside `Observable.create` or `Single.create` that calls `emitter.onError(e)` after the downstream disposed, for example from a late callback. - **An `onError` lambda that throws.** The lambda subscriber cannot deliver the second failure anywhere, so it sends both errors to the hook together as a `CompositeException`. ## What RxJavaPlugins.onError does 1. If the error is **not** one of the types RxJava treats as a likely bug, it is wrapped in `UndeliverableException`, keeping the original as the cause. The pass-through types are `OnErrorNotImplementedException`, `MissingBackpressureException`, `QueueOverflowException`, `IllegalStateException`, `NullPointerException`, `IllegalArgumentException` and `CompositeException`. 2. If an application handler was installed with `RxJavaPlugins.setErrorHandler`, it receives the error, and that is all. 3. Otherwise RxJava prints the stack trace and calls the current thread's `UncaughtExceptionHandler`. On a desktop JVM's executor thread that may only log; **on Android it terminates the app**. `UndeliverableException` itself extends `IllegalStateException`, which matters when you classify errors in a handler. ## Installing a handler The handler belongs to the **final application**, set once in `Application.onCreate()`; RxJava's own documentation advises libraries not to change it outside their tests. A useful handler triages instead of muting: - Unwrap `UndeliverableException` to get the real cause **before** testing other types, because the wrapper is an `IllegalStateException`. - Ignore causes that are expected after cancellation: `IOException` (including `SocketException` and `InterruptedIOException`) and `InterruptedException`. - Send likely bugs (`NullPointerException`, `IllegalArgumentException`, `IllegalStateException`, `OnErrorNotImplementedException`) to the thread's uncaught exception handler or to crash reporting, so they still crash in development. - Log everything else as a warning with its stack trace; a recurring warning points at a source that needs fixing. A no-op handler (`RxJavaPlugins.setErrorHandler { }`) stops the crashes but also hides `OnErrorNotImplementedException` from a subscribe that forgot `onError`, which is a real bug. ## Fixing the source rather than muting it - In `create` sources, call `emitter.tryOnError(e)`: it returns `false` instead of calling `RxJavaPlugins.onError` when the downstream is already disposed or terminated. - Register cleanup with `emitter.setCancellable { ... }` or `setDisposable(...)`, so the underlying callback or request is torn down on disposal and stops producing signals. - In blocking code you wrap, check `isDisposed()` before reporting an `InterruptedException` caused by cancellation. - Prefer sources that cancel cleanly on disposal over a blocking call wrapped in `fromCallable`. ## Reading the crash report - The top of the trace is RxJava's own plumbing (`RxJavaPlugins.onError` and the uncaught handler); the useful part is the `Caused by:` section, which holds the original exception. - The wrapper keeps its own stack trace, which can help show where in the chain the error was rerouted, and so which operator and source sit behind it. - A cause such as `InterruptedIOException` or `SocketException`, clustered around screen exits and rotations, is cancellation noise from a disposed network or disk call. - A cause such as `NullPointerException` or `IllegalArgumentException` is a bug that merely surfaced late; fix it rather than filter it. ## Testing the behaviour - Install a recording handler in a test, provoke the late error (dispose, then let the source fail), and assert what was recorded. - Call `RxJavaPlugins.reset()` after each test so one test's handler does not leak into the next.
- Why not just install a no-op RxJavaPlugins.setErrorHandler { }?It hides real bugs. Everything RxJava cannot deliver lands there, including `OnErrorNotImplementedException` from a subscribe without `onError`, `NullPointerException` from a null value and protocol violations. Unwrap `UndeliverableException`, ignore only causes you expect after cancellation, such as `IOException` and `InterruptedException`, and report the rest.
- How do you stop your own Observable.create source from producing undeliverable errors?Call `emitter.tryOnError(error)` instead of `emitter.onError(error)`: when the downstream has already disposed or terminated, it returns `false` rather than routing the error to `RxJavaPlugins.onError`. Also register cleanup with `setCancellable` or `setDisposable`, so disposal tears down the underlying callback and it stops producing signals.
- Why is a handler that rethrows every IllegalStateException a trap?`UndeliverableException` extends `IllegalStateException`, so that check matches every wrapped error, including harmless network cancellations, and crashes on all of them. Test for `UndeliverableException` first and classify its cause instead.
- Disposing a subscription guarantees no error from that chain can surface later.
- RxJava silently drops any error that arrives after dispose().
- UndeliverableException always means RxJava itself has a bug.
- Installing a no-op RxJavaPlugins error handler is the complete fix.
- Each library module should install its own global RxJavaPlugins error handler.