skip to content

In Jetpack Compose, how do you register a sensor listener with DisposableEffect so that it is removed reliably, and when does onDispose run?

level: middleimportance: must knowfreq 65%

answer

  1. cleanup paired with setup
  2. last statement of the block
  3. key change or leaving
  4. background is not leaving

basics

~10 s

Register the listener inside DisposableEffect(sensorManager) and unregister it in onDispose, the block's last statement. onDispose runs once per effect run: before the effect re-runs for a changed key, and when the effect leaves composition.

solid answer

~40 s

`DisposableEffect(key) { register(); onDispose { unregister() } }` is a `remember(key)` of an object whose setup runs when the composition applies and whose `onDispose` runs when it is forgotten. The block must end with `onDispose`, because it has to return the `DisposableEffectResult` that `onDispose` builds, so forgetting cleanup does not compile. Compose guarantees one dispose for every setup: when a key changes, the old `onDispose` runs, then the block runs again for the new key; when the effect leaves composition, `onDispose` runs. Both run on the composition's apply dispatcher, the UI thread on Android. The trap on a compass screen is that pressing Home only stops the Activity: the composition stays, so the listener stays registered. If it should stop in the background, pair it with the lifecycle instead (`LifecycleStartEffect` with `onStopOrDispose`).

code

kotlin · 23 lines
kotlin
@Composable
fun CompassSensor(
    sensorManager: SensorManager,
    onReading: (FloatArray) -> Unit,
) {
    val currentOnReading by rememberUpdatedState(onReading)

    DisposableEffect(sensorManager) {
        val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
        val listener = object : SensorEventListener {
            override fun onSensorChanged(event: SensorEvent) {
                currentOnReading(event.values.clone())
            }

            override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
        }
        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI)

        onDispose {
            sensorManager.unregisterListener(listener)
        }
    }
}

go deeper

for a junior

Recall the shape: register in the DisposableEffect block, unregister in onDispose, which must be the last statement.

for a middle

Explain the remember-based mechanism, the one-dispose-per-setup guarantee and the order on a key change: old onDispose first, then the new setup.

for a senior

Show that composition and lifecycle differ: a backgrounded screen keeps its effects, so battery-heavy listeners need lifecycle-aware pairing.

for a principal

Set the expectation that every external registration in a composable has an owner and a teardown, reviewed like any resource leak.

## The problem DisposableEffect solves Some work done for a composable must be **undone**: a sensor listener registered with `SensorManager`, a `LifecycleObserver` added to a lifecycle, a broadcast receiver, a callback set on a non-Compose object. Registering it directly in the composable body is wrong twice over: the body runs on every recomposition (registering again and again), and a composition can be abandoned before it is applied, so the registration might happen for UI that never appears. `DisposableEffect` gives the registration a **lifetime** that Compose manages. ## How it works `DisposableEffect(key1) { ... }` is, in the runtime source, `remember(key1) { DisposableEffectImpl(effect) }`. That object is a `RememberObserver`: - `onRemembered()` runs your block and stores the `DisposableEffectResult` it returns; - `onForgotten()` calls that result's `dispose()`, which is the lambda you passed to `onDispose`; - `onAbandoned()` does nothing, because a composition that was never applied never ran your setup. So setup runs **after** the composition that contains the effect has been applied, never in the middle of composing. The source states it plainly: there is one call to dispose for every call to the effect, and both run on the composition's apply dispatcher, never concurrently with applying changes to the tree. ## The onDispose contract The block's type is `DisposableEffectScope.() -> DisposableEffectResult`. The only way to produce that result is `onDispose { ... }`, so it has to be the **last statement**. Leaving it out is a type error, not a style warning. The guide adds that an empty `onDispose` is a smell: if there is nothing to undo, `SideEffect` (no cleanup) or `LaunchedEffect` (a coroutine) fits better. As with `LaunchedEffect`, the keyless `DisposableEffect { }` overload is deprecated at ERROR level, so every disposable effect must name its keys. ## When onDispose runs 1. **A key changes.** The old effect is forgotten and the new one remembered in the same apply; the runtime dispatches forgets before remembers, so the old `onDispose` runs first and the block then runs again for the new key. 2. **The effect leaves composition.** A conditional branch turns false, a navigation destination is popped, or the composition itself is disposed (for example when the Activity is destroyed). 3. **Never on its own for lifecycle events.** Pressing Home stops the Activity but does not dispose the composition, so the effect, and your listener, stay alive. | Event | onDispose runs? | |---|---| | Recomposition with equal keys | No | | A key changes | Yes, then the block runs again | | The call leaves composition | Yes | | The Activity goes to the background (`ON_STOP`) | No | | The Activity is destroyed and its composition disposed | Yes | ## Keys for a listener Key on the object you subscribe to: `DisposableEffect(sensorManager)`. If that object changes and is not a key, the old one keeps the listener and the new one never gets it; the guide gives exactly this failure with a `lifecycleOwner` that was left out of the keys. Callbacks the listener calls (`onHeadingChange`) should usually **not** be keys, because a parent may pass a new lambda on every recomposition and you would unregister and register again each time; read them through `rememberUpdatedState` instead. ## When the listener must follow the lifecycle For a compass, a listener that keeps sampling while the app sits in the background drains the battery. Two options: - a `DisposableEffect(lifecycleOwner)` that adds a `LifecycleEventObserver` and registers the sensor on `ON_START`, unregistering on `ON_STOP` and in `onDispose`; - `LifecycleStartEffect(sensorManager) { ...; onStopOrDispose { ... } }` from the lifecycle-runtime-compose artifact, which pairs start with stop or disposal for you. Either way, `DisposableEffect` remains the primitive: it ties cleanup to the composition, and the lifecycle decides the rest. ## Mistakes that leak or double-register - **Registering in the body and unregistering in `onDispose`.** The body runs on every recomposition, so the listener is registered many times and unregistered once. - **An empty `onDispose {}` to satisfy the compiler.** The listener is never removed, and the screen leaks it and the objects it captures each time it is shown. - **Keying on a callback.** Each new lambda from the parent disposes and re-registers the listener for no reason. - **Doing slow work in setup.** Setup and `onDispose` run on the UI thread during apply; a blocking call there delays the frame. Start heavy work from a coroutine instead.

  • In Jetpack Compose, why does setup inside DisposableEffect never run for a composition that is thrown away?
    Setup runs in `onRemembered()`, which Compose dispatches only when a composition is applied. If a composition is abandoned, the remembered object gets `onAbandoned()` instead, and `DisposableEffectImpl` does nothing there, because its setup never ran and there is nothing to undo.
  • In Jetpack Compose, what should a DisposableEffect key be when it observes an Activity's lifecycle?
    The `LifecycleOwner` it adds the observer to, typically `LocalLifecycleOwner.current`. If the owner changes and is not a key, the observer stays on the old lifecycle and the effect silently watches the wrong one. Callbacks invoked from the observer are read through `rememberUpdatedState` rather than added as keys.

  • onDispose runs when the Activity goes to the background
  • Registering in the composable body and unregistering in onDispose is equivalent
  • onDispose is optional; without it the effect just never cleans up
  • When a key changes, the new effect runs before the old onDispose
  • Every callback the listener calls should be a DisposableEffect key