Side effects: LaunchedEffect and friends

Learn how to manage side effects in Jetpack Compose with LaunchedEffect, DisposableEffect, and more to control coroutines and state in Android. About 25 minutes.

Why it matters

  • LaunchedEffect and DisposableEffect are the standard ways to start coroutines or register listeners from a composable; doing it in the body runs on every recomposition and causes duplicate work.
  • Keys control restarts. A wrong key means a request for the old id keeps running, a timer restarts too often, or a listener stays registered on the wrong object.
  • Interviewers ask 'what happens when the key changes' and 'what happens when the composable leaves composition' because those two paths are where many production bugs live.
  • rememberUpdatedState and derivedStateOf prevent two separate classes of bug: a long-running effect calling an old callback, and unnecessary recompositions from a calculated value.

The simple explanation

  • A LaunchedEffect is like a kitchen timer you set for a specific dish. Change the dish (the key), and the old timer is thrown away and a new one starts.
  • DisposableEffect is like a subscription: you sign up when it starts, and you must cancel when you leave or switch plans.
  • SideEffect is like updating the specials board after every finished round of cooking, so the front of house always sees the latest menu.
  • rememberUpdatedState is like a whiteboard with the latest phone number: a timer that has been running for a while still calls the current number, not the one from when it started.

Compose separates composition (describing the UI) from side effects (work that changes things outside the composition). The effect APIs live in androidx.compose.runtime.

APIWhen it runsWhen it stops or cleans up
LaunchedEffect(key1, key2, …)Launches a coroutine when it enters the composition, and again when any key changesThe coroutine is cancelled when a key changes or the effect leaves the composition
DisposableEffect(key1, key2, …)Runs its block when it enters the composition, and again when any key changesonDispose runs before a restart and when it leaves the composition
SideEffectAfter every successful composition and recomposition of the composable that calls itNo cleanup
rememberUpdatedState(value)Updates a remembered State with the latest value on every recompositionNothing to clean up
derivedStateOf { … }Recalculates when a state it reads changesNotifies readers only when the result changes
snapshotFlow { … }Runs the block again when a state it reads changes, and emits if the result differs from the last emissionStops when the collecting coroutine is cancelled

Key rules:

  • LaunchedEffect(Unit) (or any constant key) starts once when the effect enters the composition and runs until it leaves.
  • LaunchedEffect(userId) cancels the previous coroutine when userId changes and launches a new one. Cancellation is cooperative: suspending calls such as delay, withContext and collect stop with a CancellationException.
  • DisposableEffect is for callback-style resources that need cleanup: registering a LifecycleObserver, a sensor listener or a BroadcastReceiver.
  • SideEffect pushes Compose state into objects that Compose does not manage (an analytics user property, a View in a mixed UI). It runs after every successful recomposition, never during a recomposition that is thrown away.
  • rememberUpdatedState is for a value that changes across recompositions, typically a callback parameter, that a long-running effect must use without restarting. A by remember { mutableStateOf(...) } variable does not need it: reading it inside the coroutine already gives the current value.
  • derivedStateOf is for when inputs change more often than the result: listState.firstVisibleItemIndex > 0 flips rarely while the index changes constantly.
  • snapshotFlow turns state reads into a cold Flow. Collect it in a coroutine such as a LaunchedEffect to use operators like filter, debounce or distinctUntilChanged on Compose state.
When a LaunchedEffect restarts
When a LaunchedEffect restarts When the composable enters the composition, LaunchedEffect launches a coroutine. A recomposition with the same key does nothing. When the key changes, the old coroutine is cancelled and a new one starts. When the composable leaves the composition, the coroutine is cancelled. Nothing happens ENTERS COMPOSITION LAUNCH RECOMPOSE, SAME KEY RECOMPOSE, NEW KEY CANCEL THE OLD ONE LAUNCH A NEW ONE LEAVES COMPOSITION CANCEL Composable recomposes LaunchedEffect (key) Coroutine the effect's work
Same key, nothing happens. A new key cancels the running coroutine and starts a fresh one. Leaving the composition cancels it.

Notes

  • LaunchedEffect(key) cancels the previous coroutine when key changes. Cancellation is cooperative: delay, withContext and collect respond to it. Blocking code such as Thread.sleep does not stop early.
  • Keys are compared with equals. Use every value the effect uses and that should restart it as a key; a constant key means "start once".
  • DisposableEffect must end with an onDispose { } block (the code does not compile without it). An empty onDispose is a smell: something was registered and never removed.
  • SideEffect runs after every successful composition and recomposition. Use it to sync Compose state into a non-Compose object, not for one-time work.
  • rememberUpdatedState(value) returns a State<T> that always holds the latest value. Read it inside the long-running effect, usually with val current by rememberUpdatedState(onTimeout).
  • derivedStateOf { … } must be wrapped in remember. It helps only when the result changes less often than its inputs.
  • snapshotFlow { … } emits when the result of its block changes. Collect it in LaunchedEffect to react to state changes with Flow operators.
  • rememberCoroutineScope() gives a scope that is cancelled when the composable leaves the composition. Use it to launch work from callbacks such as onClick, which are not composable. Use LaunchedEffect for work driven by keys.
  • Separate effects run as separate coroutines. Do not rely on one effect finishing before another starts.
  • LaunchedEffect(userId, filter) restarts when any key changes. If parts of the work have independent lifecycles, use separate effects.
  • Data loading usually belongs in the ViewModel. Effects in composables are for UI-scoped work: animations, snackbars, listeners, scrolling.

Code example

This screen loads a profile when userId changes, cancels the old request, calls the latest callback through rememberUpdatedState, and observes the lifecycle with DisposableEffect.

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.compose.LocalLifecycleOwner
 
data class UserProfile(val name: String)
 
interface UserApi {
    suspend fun fetchUser(id: Int): UserProfile // main-safe
}
 
@Composable
fun UserProfileScreen(
    userId: Int,
    api: UserApi,
    onProfileShown: (UserProfile) -> Unit,
) {
    var loading by remember { mutableStateOf(false) }
    var profile by remember { mutableStateOf<UserProfile?>(null) }
 
    // The effect below must not restart when the parent passes a new lambda,
    // but it must call the latest one.
    val currentOnProfileShown by rememberUpdatedState(onProfileShown)
 
    // Keyed on userId: a change cancels the old request and starts a new one
    LaunchedEffect(userId) {
        loading = true
        val result = api.fetchUser(userId) // a cancelled coroutine stops here
        profile = result
        loading = false
        currentOnProfileShown(result)
    }
 
    // Keyed on the owner: if it changes, remove from the old one, add to the new one
    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(lifecycleOwner) {
        val observer = object : DefaultLifecycleObserver {
            override fun onStart(owner: LifecycleOwner) { /* e.g. resume a player */ }
            override fun onStop(owner: LifecycleOwner) { /* e.g. pause it */ }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
    }
 
    Column {
        if (loading) CircularProgressIndicator()
        profile?.let { Text(it.name) }
    }
}
  • When userId changes, the old coroutine is cancelled at its suspension point inside fetchUser, so it never writes its stale result. No try/catch is needed for that; catching CancellationException and carrying on would be a bug.
  • rememberUpdatedState is used for the callback parameter, not for loading. loading is Compose state, so reading it anywhere already gives the current value.
  • LocalLifecycleOwner.current is read in the composable body, outside the effect. Composable reads are not allowed inside onDispose or the observer.
  • Error handling is left out to keep the example short. In a real app this loading belongs in a ViewModel that exposes a UiState.

Run the idea in plain Kotlin

A small model of one keyed effect: same key, nothing happens; new key, cancel then start; leaving the composition, cancel.

class KeyedEffect {
  private var currentKey: Any? = null
  private var active = false

  fun compose(key: Any?) {
      if (active && key == currentKey) {
          println("  same key " + key + ": effect keeps running")
          return
      }
      if (active) println("  cancel work for key " + currentKey)
      currentKey = key
      active = true
      println("  start work for key " + key)
  }

  fun leave() {
      if (active) println("  cancel work for key " + currentKey)
      active = false
  }
}

fun main() {
  val effect = KeyedEffect()
  println("first composition, userId = 1")
  effect.compose(1)
  println("recomposition, userId = 1")
  effect.compose(1)
  println("recomposition, userId = 2")
  effect.compose(2)
  println("composable leaves composition")
  effect.leave()
}

Expected output:

first composition, userId = 1
  start work for key 1
recomposition, userId = 1
  same key 1: effect keeps running
recomposition, userId = 2
  cancel work for key 1
  start work for key 2
composable leaves composition
  cancel work for key 2

In production

Duplicate network calls on every recomposition
  • The backend team saw several identical profile requests for each screen open.
  • The app called viewModel.loadProfile(userId) directly in the composable body instead of inside an effect.
  • Every recomposition (a state update, a theme change, an animation) ran the body again and started another request.
The fix
  • Short term: moved the call into LaunchedEffect(userId), so it runs when the screen enters the composition and when userId changes.
  • Better: the ViewModel starts loading itself (in init, from a SavedStateHandle id, or through stateIn), so the composable only collects state.
  • Added a Compose UI test with a fake repository that forces several recompositions and asserts one request.
A lifecycle observer that outlived its screen
  • LeakCanary reported a leaked settings screen object after users navigated away.
  • The screen used DisposableEffect(Unit) to add a LifecycleObserver to the Activity's lifecycle, but onDispose was left empty with a TODO.
  • The Activity's lifecycle kept a reference to the observer, and the observer held the screen's objects, so they stayed in memory and kept reacting to lifecycle events.
The fix
  • Implemented onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }.
  • Changed the key from Unit to lifecycleOwner, so the observer moves if the owner changes.
  • Kept LeakCanary in debug builds and added "empty onDispose" to the code review checklist.

Common mistakes

  • Putting a network call in the composable body. The body runs on every recomposition, so the call fires repeatedly. Move it into the ViewModel, or into LaunchedEffect(key) so it runs only when the key changes.
  • Using LaunchedEffect(Unit) for work that depends on a value. A constant key never changes, so the effect never restarts and keeps using the old value. Use the actual value as the key.
  • Calling a callback parameter from a long-running effect without rememberUpdatedState. The effect keeps the lambda from its first composition and calls an old version. Use val current by rememberUpdatedState(onDone) and call current().
  • Leaving onDispose empty. The observer, listener or receiver is never removed, so it leaks and keeps firing. Undo every registration in onDispose.
  • Using SideEffect for a one-time action. SideEffect runs after every successful recomposition, not just the first. For a one-time action use LaunchedEffect(Unit).
  • Using derivedStateOf when the result changes as often as its inputs. For fullName = first + last, every input change changes the result, so derivedStateOf only adds overhead. Compute it directly in the body.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What happens when the key of a LaunchedEffect changes?”

“When would you choose DisposableEffect over LaunchedEffect?”

“What is rememberUpdatedState and when do you need it?”

“How does derivedStateOf reduce recomposition?”

Quiz

What happens to the coroutine inside LaunchedEffect(userId) when userId changes from 1 to 2?

Which API should you use to register a LifecycleObserver and remove it when the composable leaves composition?

A composable calls its onTimeout parameter from LaunchedEffect(Unit) after delay(5000). The parent passes a new onTimeout lambda after 2 seconds. Without rememberUpdatedState, which lambda runs?

When does SideEffect run?

0 of 4 answered

Mini task

Exercise: Keyed fetch with cancellation and cleanup (15 min)

  1. Create a screen DataScreen(itemId: Int, onLoaded: (String) -> Unit).
  2. Add a LaunchedEffect(itemId) that sets loading = true, calls a fake API (delay(1000) and then return a string), stores the result and sets loading = false.
  3. Wrap the body of the effect in try { ... } finally { Log.d("Data", "effect for $itemId ended") }. Add Log.d lines for "start" and "done" too. Do not catch CancellationException.
  4. Read onLoaded through val currentOnLoaded by rememberUpdatedState(onLoaded) and call currentOnLoaded(result) at the end of the effect.
  5. Add a DisposableEffect(Unit) that logs on enter and logs again in onDispose.
  6. Run the app. Change itemId from 1 to 2 while the first fetch is in flight. In Logcat, check that item 1 shows "start" and "ended" but no "done", and item 2 shows "start", "done" and "ended".
  7. Navigate away from the screen. Confirm the onDispose log appears.

Done condition: Logcat shows the first fetch cancelled without "done", one completed fetch for item 2, and one dispose log when you leave. Recomposing the screen for other reasons (for example toggling an unrelated state) starts no new fetch.

Next: XML layouts and ViewBinding