DisposableEffect

Jetpack Compose Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Fill the blank

Complete the cleanup so the observer doesn't leak.

@Composable
fun TrackResume(onResume: () -> Unit) {
    val owner = LocalLifecycleOwner.current
    DisposableEffect(owner) {
        val observer = LifecycleEventObserver { _, e -> if (e == Lifecycle.Event.ON_RESUME) onResume() }
        owner.lifecycle.addObserver(observer)
        ____ { owner.lifecycle.removeObserver(observer) }
    }
}
Options
Hint 1 of 1

What must the DisposableEffect block return?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A onDispose

Correct. onDispose runs when the effect leaves composition or its key changes.

Why not the others?
  • B finally. This isn't a try block; DisposableEffect must return onDispose.
  • C awaitClose. awaitClose belongs to callbackFlow.
  • D SideEffect. SideEffect runs after every successful recomposition, not on disposal.

30-second answer

Use DisposableEffect for non-suspending setup that needs matching cleanup: register a listener or observer when entering composition, unregister in onDispose when leaving or when keys change. LaunchedEffect is for suspend work. The onDispose block is required, which makes forgetting cleanup a compile error.

Practise saying it · 30 s. No recording, just a timer

Explain DisposableEffect.

Say your answer out loud, then check which of these points you covered:

  • Non-suspending setup with cleanup
  • onDispose is required
  • Keys restart it
  • LifecycleStartEffect for lifecycle cases

Deep dive

Common uses: lifecycle observers, broadcast receivers, sensor listeners, back callbacks in legacy code.

Keys work like LaunchedEffect: changing a key disposes the old effect and starts a new one.

LifecycleResumeEffect and LifecycleStartEffect wrap the common lifecycle case.

Keep the effect small; move the listener logic into a state holder if it grows.

Common mistakes

  • Registering a listener in the composable body.
  • Forgetting keys, so a listener keeps the old callback.
  • Doing suspend work in DisposableEffect.

Senior take & follow-ups

Name a real example, such as a lifecycle observer, and say what happens on key change.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you observe the lifecycle in a composable?

    Show hint

    DisposableEffect(lifecycleOwner) adding and removing an observer, or LifecycleStartEffect.

  2. Why is onDispose mandatory?

    Show hint

    So every registration has a matching cleanup.

Suggest a fix if something here is wrong or out of date.