In Jetpack Compose, what do the keys passed to LaunchedEffect decide, and what goes wrong when you choose the wrong ones?
answer
- identity of the effect
- remember with the same keys
- cancel, then relaunch
- Unit means the call site's lifetime
basics
~20 sLaunchedEffect's keys are its identity: its coroutine starts when it enters composition, is cancelled and relaunched when any key changes by equals(), and is cancelled when it leaves. Too few keys leave stale work running; unstable keys restart it constantly.
solid answer
~50 s`LaunchedEffect(key1, key2) { ... }` is a `remember(key1, key2)` of an object that launches the block when it is remembered and cancels the job when it is forgotten. So the coroutine starts when the effect enters composition, keeps running across recompositions while every key is `equals()` to its previous value, is cancelled and relaunched in a new coroutine when any key changes, and is cancelled when the effect leaves composition. The rule of thumb: every value the block reads that should restart the work is a key; a value that may change without restarting it goes through `rememberUpdatedState`. Too few keys and the effect keeps working on an old download id; a key that is a new object without value equality restarts the work on every recomposition. `Unit` or `true` tie the effect to the call site's lifetime, and the keyless overload does not compile.
code
kotlin · 26 lines@Composable
fun DownloadStatus(
downloadId: Long,
downloads: DownloadRepository,
snackbarHostState: SnackbarHostState,
) {
var progress by remember { mutableIntStateOf(0) }
// Restarts only when the download being watched changes.
LaunchedEffect(downloadId) {
progress = 0
downloads.progress(downloadId).collect { percent ->
progress = percent
}
// The flow completed without reaching 100: report the failure.
if (progress < 100) {
snackbarHostState.showSnackbar("Download $downloadId failed")
}
}
LinearProgressIndicator(progress = { progress / 100f })
}
interface DownloadRepository {
fun progress(id: Long): kotlinx.coroutines.flow.Flow<Int>
}go deeper
Recall that LaunchedEffect runs a suspend block when it enters composition, restarts when a key changes and is cancelled when it leaves.
Explain that the effect is a remember keyed on its keys, compared with equals, and that the keyless overload is a compile error by design.
Diagnose effects that restart on every frame or never restart, and fix them by choosing keys or moving values into rememberUpdatedState.
Treat effect keys as a review checklist item: every read value is either a key or deliberately read through rememberUpdatedState, and one-shot events carry an id.
## What a LaunchedEffect actually is `LaunchedEffect` is a **composable that emits no UI** and runs a suspending block in a coroutine owned by the composition. Its implementation in Compose runtime is short: it calls `remember(keys) { LaunchedEffectImpl(applyContext, block) }`. That object is a `RememberObserver`: - in `onRemembered()` it **launches** the block into the composition's coroutine context; - in `onForgotten()` (and `onAbandoned()`) it **cancels** that job with a cancellation exception whose message says the coroutine left the composition. Everything about keys follows from that one `remember` call. The keys are not arguments the block receives; they are the **identity** of the effect. ## The lifecycle of the coroutine, step by step 1. **Enter.** The first time `LaunchedEffect(downloadId)` is composed, the object is remembered once the composition applies, and the block starts. 2. **Recompose with equal keys.** Compose compares each key with the stored one using `equals()`. If all are equal, `remember` returns the existing object and the running coroutine is untouched, even though the block lambda passed this time may be a different instance. 3. **Recompose with a changed key.** The old object is forgotten, so its job is cancelled; a new object is remembered and launches the block again, in a **new** coroutine. 4. **Leave.** When the call stops being composed (an `if` branch turns false, a navigation destination is removed, the whole composition is disposed when an Activity is recreated by default on a configuration change), the job is cancelled. The block runs on the composition's apply dispatcher, which on Android is the window's UI thread, so suspending calls are fine and blocking calls are not. ## Choosing keys The guide's rule of thumb: the values the block uses should be keys, unless a change to them should not restart the work. - **A value whose change means "start over"** is a key: the download id whose progress you observe, the user id whose profile you load. - **A value whose change should be seen but should not restart** (an `onFailed` callback, the latest message text) is read through `rememberUpdatedState` instead of being a key. - **A value that never changes** because it is held in a `remember` with no keys need not be a key. - **A constant** (`Unit`, `true`) makes the effect live exactly as long as its call site. The guide warns that `LaunchedEffect(true)` deserves the same suspicion as `while (true)`: valid, but check that you mean it. | Mistake | Symptom | |---|---| | A key missing | The effect keeps working on the old download id after the screen shows a new one | | A key that is a new object on every recomposition without value equality | The work is cancelled and restarted on every recomposition | | A constant where a changing input belongs | The block never sees the new input | | A key holding click data in a `MutableState` | An event modelled as state; the runtime docs point you to `rememberCoroutineScope` instead | ## The keyless overload is a compile error `LaunchedEffect { ... }` with no key matches an overload marked `@Deprecated(level = DeprecationLevel.ERROR)`. Its message says the effect must provide one or more keys that define its identity. The same holds for `DisposableEffect`. The point of the error is to make you choose a lifetime on purpose. ## Effects that "run twice" A one-shot action written as `LaunchedEffect(Unit) { snackbarHostState.showSnackbar(error) }` runs again whenever the call site enters composition again. Two common causes: - The Activity is recreated on a configuration change, the composition is rebuilt, and the effect enters a new composition, so a failure kept in a longer-lived holder is shown a second time. - The call sits in a list without a stable identity, so moving items makes Compose treat the call as new and the effect restarts. The fix is to key on the thing that identifies the event (an error id) and to mark the event handled once shown, not to hunt for a constant that survives recreation. Holding that state outside the composition is a ViewModel matter, outside this lesson. ## Where the coroutine rules come in Cancelling the job is cooperative, exactly as for any coroutine; how cancellation propagates, why a `catch (e: Exception)` can swallow it, and how child jobs behave are covered in the lesson on Kotlin coroutines. What Compose adds is only **when** the cancel happens: key change and leaving composition.
- In Jetpack Compose, does passing a new block lambda with the same keys restart a LaunchedEffect?No. Only the keys go into the `remember`; the block passed on a later recomposition is ignored while the keys are equal, and the coroutine keeps running the block it started with. That is exactly why a value read inside the block can go stale, and why such a value is either a key or read through `rememberUpdatedState`.
- In Jetpack Compose, how are LaunchedEffect keys compared?With `equals()`, one key at a time against the value stored in the slot table. A data class rebuilt with the same contents is therefore equal and does not restart the effect; an object whose class does not override `equals()`, created anew each recomposition, is a new key every time and restarts it on every recomposition.
- In Jetpack Compose, why does LaunchedEffect(Unit) not mean 'run once per app session'?`Unit` only ties the effect to its call site. Whenever that call site leaves and re-enters composition (navigating back to the screen, an Activity recreated on a configuration change, a conditional branch toggling) the effect is a new one and runs again.
- LaunchedEffect restarts its block on every recomposition of the caller
- The block receives the new key values while it keeps running
- LaunchedEffect without keys runs once, like LaunchedEffect(Unit)
- Keys are compared by reference, so equal data classes restart the effect
- LaunchedEffect(Unit) runs once for the lifetime of the app
- Changing a key lets the old coroutine finish before the new one starts