Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 104 ยท State in Compose

Side Effects: LaunchedEffect, DisposableEffect and Friends

Learn when and how to run side effects in Jetpack Compose: LaunchedEffect keys, rememberCoroutineScope, DisposableEffect cleanup, SideEffect, produceState.

A composable should describe UI. It may run many times, in any order, and it may be abandoned halfway. That is why it must not start a network request, register a listener, write to a log file or show a toast directly in its body: those things would happen again and again, or leak. But real screens need exactly such work, such as loading data when a screen appears, subscribing to a sensor, or telling analytics which screen is visible.

Compose solves this with effect handlers: functions that run your side effect at a controlled moment in the composable's life, tie it to the composition so that it is cleaned up, and restart it when its inputs change. This lesson covers the important ones. The Compose and Android code is read-only because it needs the SDK. The TryIt blocks are Kotlin stand-ins that model the effect lifecycle (start, restart on a new key, clean up) with plain functions. They are not the real runtime, but the rules they demonstrate are the real rules.

The lifecycle of a composable

A composable that shows on screen goes through three events: it enters the composition, it may be recomposed any number of times, and it leaves the composition. Effect handlers are tied to the first and last event: they start when the composable enters and they are cancelled or disposed when it leaves. The keys you give them decide whether they also restart in between.

flowchart LR
    E["Enters composition<br/>effect starts"] --> R["Recompositions<br/>(effect keeps running<br/>if keys are equal)"]
    R --> K["Key changes<br/>cancel + restart"]
    K --> R
    R --> L["Leaves composition<br/>cancel / dispose"]

Effects start on entry, restart only when a key changes, and are cancelled when the composable leaves.

LaunchedEffect: run suspending work

LaunchedEffect(key) { ... } runs a suspend block in a coroutine that is scoped to the composition. It launches when the composable enters the composition. If key later changes, the running coroutine is cancelled and a new one is launched with the new key. When the composable leaves, the coroutine is cancelled.

Kotlin
// read-only example: needs Compose and coroutines
@Composable
fun UserScreen(userId: String, viewModel: UserViewModel) {
    LaunchedEffect(userId) {
        viewModel.load(userId)       // restarts only when userId changes
    }
    // ...
}

Choose keys deliberately:

  • A key that is the value the effect depends on (userId) is the usual choice: new user, new load.
  • LaunchedEffect(Unit) or LaunchedEffect(true) means "run once while this composable is in the composition". Use it only when the work really depends on nothing.
  • Do not pass a key that changes every recomposition (a new object, a timestamp): the effect would restart every time.
  • Several keys are allowed: LaunchedEffect(userId, refreshToken) restarts when either changes.

Because the block is a coroutine, it can call delay, collect a Flow or use withContext. Cancellation works like everywhere else in Kotlin coroutines (Cancellation): a cancelled effect throws CancellationException at its next suspension point, so a finally block still runs.

rememberCoroutineScope: effects from callbacks

LaunchedEffect starts work because the composition changed. If you need to start a coroutine because the user did something, for example in an onClick, you cannot call LaunchedEffect there (it is a composable). Use a scope remembered by the composition:

Kotlin
// read-only example: needs Compose and coroutines
@Composable
fun SaveButton(onSave: suspend () -> Unit, snackbarHostState: SnackbarHostState) {
    val scope = rememberCoroutineScope()
    Button(onClick = {
        scope.launch {
            onSave()
            snackbarHostState.showSnackbar("Saved")
        }
    }) { Text("Save") }
}

The scope is cancelled when the composable leaves the composition. Never call scope.launch in the composable body itself: that would start a new coroutine on every recomposition. Work that must outlive the screen (a download, a payment) does not belong in either; give it to a ViewModel or WorkManager.

A stand-in for effect restarts

The TryIt below models the two most important behaviors: a launched effect that is cancelled and restarted when its key changes, and a disposable effect with cleanup. Composition remembers, per effect id, the last key and the running job. Each call to launchedEffect or disposableEffect is like a recomposition reaching that line: if the key is equal nothing happens, otherwise the old one is cancelled and the new one starts.

A coroutine is modeled by an iterator that yields a message at each "suspension point", and frame() advances every running job by one step. Cancelling a job just stops advancing it. This is a simplification: real coroutines run concurrently on a dispatcher, here everything is stepped by hand so the output is the same every time.

Kotlin Effects that cancel and restart on key change (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output from the top: the first load job was stopped after two steps when the key changed from 1 to 2, the listener was unregistered before the new one was registered, and screen(1) the second time did nothing at all.

DisposableEffect: set up and clean up

Some effects are not coroutines but subscriptions: you register something now and must unregister it later, for example a lifecycle observer, a broadcast receiver or a sensor listener. DisposableEffect is built for that. Its block must end with onDispose { ... }, which runs when the effect leaves the composition or before it restarts because a key changed.

Kotlin
// read-only example: needs Compose and AndroidX Lifecycle
@Composable
fun LogLifecycle(owner: LifecycleOwner = LocalLifecycleOwner.current) {
    DisposableEffect(owner) {
        val observer = LifecycleEventObserver { _, event ->
            Log.d("Screen", "event: $event")
        }
        owner.lifecycle.addObserver(observer)
        onDispose { owner.lifecycle.removeObserver(observer) }
    }
}

If you forget onDispose, the code does not compile: the compiler insists on it, because a missing cleanup is a leak. Use DisposableEffect whenever there is something to undo; use LaunchedEffect whenever the work is suspending.

rememberUpdatedState: long effects with fresh callbacks

A LaunchedEffect that is keyed on Unit runs once and keeps running. If it uses a lambda parameter (say onTimeout) the effect captured the first lambda it saw. After a recomposition the caller may pass a different lambda that sees newer state, but the long-running effect still holds the old one. Restarting the effect to refresh it would reset a timer, which you usually do not want.

rememberUpdatedState solves this: it returns a State that always holds the latest value, while the effect captures the stable holder instead of the value.

Kotlin
// read-only example: needs Compose and coroutines
@Composable
fun SplashScreen(onTimeout: () -> Unit) {
    val currentOnTimeout by rememberUpdatedState(onTimeout)
    LaunchedEffect(Unit) {
        delay(3_000)
        currentOnTimeout()          // the newest lambda, timer not restarted
    }
}

The stand-in below shows the difference. Without the holder the effect fires the lambda it captured at start; with the holder it fires the latest one.

Kotlin Stale capture vs rememberUpdatedState (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

SideEffect and produceState

Two smaller handlers round out the set:

  • SideEffect { ... } runs after every successful recomposition. Use it to publish Compose state to non-Compose code that must always know the latest value, such as a crash reporter: SideEffect { crashReporter.setScreen(name) }. It has no keys and no cleanup, and it must be quick.
  • produceState(initialValue, key) { ... } converts non-Compose, possibly suspending data into Compose State. The block runs in a coroutine like LaunchedEffect, and assigning value updates the state:
Kotlin
// read-only example: needs Compose and coroutines
@Composable
fun rememberOnline(connectivity: ConnectivityMonitor): State<Boolean> =
    produceState(initialValue = false, connectivity) {
        connectivity.status.collect { value = it }
    }

For a Flow that comes from a ViewModel you will normally use collectAsStateWithLifecycle() instead, which StateFlow and collectAsStateWithLifecycle introduces.

Choosing a handler

You want to... Use
Run suspending work when something appears or a value changes LaunchedEffect(key)
Start a coroutine from a click or other event rememberCoroutineScope()
Register a listener and unregister it later DisposableEffect(key) with onDispose
Share Compose state with non-Compose code after each recomposition SideEffect
Turn a callback or Flow into State produceState or collectAsStateWithLifecycle
Use the latest lambda inside a long-running effect rememberUpdatedState

When none of these fit, the work probably belongs outside the UI in a ViewModel.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a running LaunchedEffect when its key changes?

    Changing the key cancels the old coroutine (at its next suspension point) and launches the block again with the new key.
  2. 2. Where should you use rememberCoroutineScope instead of LaunchedEffect?

    LaunchedEffect is itself a composable and reacts to composition changes. A click handler is not composable, so it launches work in a scope obtained with rememberCoroutineScope.
  3. 3. What is required at the end of a DisposableEffect block?

    DisposableEffect must end with onDispose, which runs when the effect leaves the composition or before it restarts, so the listener or resource is released.
  4. 4. Why use rememberUpdatedState inside LaunchedEffect(Unit)?

    The effect captured its lambdas when it started. rememberUpdatedState gives it a holder whose value is refreshed on each recomposition, so the effect sees the latest one while its timer keeps running.

Summary

  • Composables must not perform side effects directly; effect handlers run them at controlled points tied to the composition.
  • LaunchedEffect(key) runs suspending work, cancels and restarts when the key changes, and is cancelled when the composable leaves. Pick keys that reflect what the work depends on.
  • rememberCoroutineScope launches coroutines from callbacks such as clicks; never launch in the composable body.
  • DisposableEffect pairs setup with a mandatory onDispose cleanup.
  • rememberUpdatedState lets a long-running effect see the latest values without restarting.
  • SideEffect publishes state after every recomposition; produceState turns other data sources into State.
  • The Compose code is read-only; the TryIt blocks are stand-ins that step through the effect lifecycle.

Next: Material 3 and Theming