In Jetpack Compose, a LaunchedEffect(Unit) waits ten seconds and then calls an onCalibrationTimeout parameter, but invokes an outdated lambda; why, and how does rememberUpdatedState fix it?
answer
- the block captured its first lambda
- keys decide restarts, not values
- one remembered State, updated each recomposition
- read the latest through the delegate
basics
~20 sThe effect's block captured the lambda from its first composition and never restarts, so later lambdas are ignored. rememberUpdatedState keeps one State updated each recomposition; the effect reads it when the timer fires, getting the latest lambda.
solid answer
~40 s`LaunchedEffect(Unit)` launches its block once and keeps that coroutine for the life of the call site; the block passed on later recompositions is ignored, so a lambda it captured stays the first one forever. Making the lambda a key would fix staleness but restart the ten-second timer whenever the parent passes a new instance. `val currentOnTimeout by rememberUpdatedState(onCalibrationTimeout)` is `remember { mutableStateOf(it) }` with its value set to the new argument on every recomposition. The effect captures that one State object and reads `currentOnTimeout` when the delay ends, so it calls whatever lambda the screen was last composed with. The same pattern serves a listener in `DisposableEffect` that calls a callback parameter: subscribe once, read the latest callback through `rememberUpdatedState`.
go deeper
Recall that an effect's block keeps the values it captured when it launched, and that rememberUpdatedState is the tool for reading the latest one.
Explain the implementation: one remembered MutableState whose value is overwritten on each recomposition, captured by the effect instead of the raw lambda.
Diagnose a timer or listener calling stale callbacks, and justify rememberUpdatedState over keying the effect on the lambda by what restarting would cost.
Make 'every value an effect reads is a key or goes through rememberUpdatedState' a review rule for shared components that take callbacks.
## The bug A compass screen shows a "move your phone in a figure eight" hint if the sensor has not calibrated after ten seconds. The parent passes `onCalibrationTimeout`, and the lambda it passes changes: the first one captures the screen's initial units setting, a later one captures the user's new choice. ```kotlin @Composable fun CalibrationTimer(onCalibrationTimeout: () -> Unit) { LaunchedEffect(Unit) { delay(10_000) onCalibrationTimeout() // the lambda from the FIRST composition } } ``` When the delay ends, the effect calls the lambda it captured when it was launched, which may close over state that is no longer current. ## Why the effect does not see the new lambda `LaunchedEffect` is `remember(keys) { LaunchedEffectImpl(..., block) }`. While the keys are equal, `remember` returns the existing object, so the block passed on a later recomposition is **never used**. The running coroutine keeps the closure it started with. That is the general rule for every long-lived effect: - **keys** decide whether the work restarts; - **values captured by the block** are frozen at launch; - anything that should be current but should not restart the work needs another channel. Strong skipping (the default since Kotlin 2.0.20) does not change this. It remembers lambdas in composition keyed on what they capture, so a lambda that captures a changed value is still a new instance, and the effect still holds the old one. ## Two fixes, one wrong for this case | Approach | Staleness fixed? | Timer behaviour | |---|---|---| | `LaunchedEffect(onCalibrationTimeout)` | Yes | Restarts from zero every time the parent passes a new lambda instance | | `rememberUpdatedState(onCalibrationTimeout)` + `LaunchedEffect(Unit)` | Yes | Runs once for the call site; the latest lambda is called when it fires | Keying on the lambda is correct only when a new callback should genuinely restart the work. For a timeout, it can postpone the hint indefinitely if the parent recomposes often. ## How rememberUpdatedState works The runtime implementation is one line: `remember { mutableStateOf(newValue) }.apply { value = newValue }`. 1. On the first composition it creates a `MutableState` holding the argument. 2. On every recomposition of the `rememberUpdatedState` call it **writes** the new argument into that same State object. 3. The effect captured the State, not the lambda, so reading it later returns the latest value. Read it with `by` delegation and call the delegate inside the effect: ```kotlin @Composable fun CalibrationTimer(onCalibrationTimeout: () -> Unit) { val currentOnTimeout by rememberUpdatedState(onCalibrationTimeout) LaunchedEffect(Unit) { delay(10_000) currentOnTimeout() // the lambda from the LATEST composition } } ``` Because the read happens inside the effect's coroutine, not during composition, the write on each recomposition does not cause extra recompositions of the screen. The timer still starts once per call site: if the screen leaves composition and comes back, a new effect and a new timer begin, which is usually what a timeout should do. ## Where else the pattern applies - **A listener in `DisposableEffect`** that calls a callback parameter: subscribe once, keyed on the subscribed object, and read the callback through `rememberUpdatedState` so a new lambda does not unregister and register the listener. - **A `snapshotFlow` collection** that calls a parameter for each emission. - **Custom effects** you build from `LaunchedEffect`: if they accept a lambda, they should use the same technique internally. ## The rule in one sentence The Compose guide states it as a key point: variables used in an effect should either be keys of the effect or be read through `rememberUpdatedState`. A value that is neither is a staleness bug waiting for the input to change. ## A checklist for any long-lived effect 1. List every value the effect's block reads. 2. For each one decide: a change should **restart** the work (make it a key), should be **seen without restarting** (read it through `rememberUpdatedState`), or **never changes** because it is remembered without keys (leave it out). 3. Check that every key has meaningful `equals()`, so equal inputs do not restart the effect. ## What not to reach for - `remember { onCalibrationTimeout }` freezes the first lambda, which is exactly the bug. - Restarting the timer manually from the parent moves effect logic out of the composable that owns it.
- In Jetpack Compose, does reading a rememberUpdatedState value inside LaunchedEffect cause the screen to recompose when the value changes?No. The value is read inside the effect's coroutine, not during composition, so no recompose scope records that read. The write happens during the caller's recomposition, which is already running for another reason. Reading the same State directly in the composable body would subscribe that scope, but that is not how the pattern uses it.
- In Jetpack Compose, when is keying a LaunchedEffect on a lambda the right choice instead of rememberUpdatedState?When a new callback genuinely means the work must start over, for example a lambda that encodes which request to run. If the callback only says what to do when the work finishes, read it through `rememberUpdatedState`; keying on it would restart the work whenever the parent passes a new instance.
A kitchen timer that, when it rings, calls whoever the shift board says is on duty: the timer is set once, but it reads the board at ring time instead of remembering the cook who set it. Swapping the name on the board does not reset the timer.
- LaunchedEffect picks up the new block lambda on every recomposition
- Strong skipping makes lambdas stable, so captured callbacks never go stale
- Adding the callback as a key is always the correct fix
- rememberUpdatedState creates a new State on each recomposition
- remember { onTimeout } keeps the lambda current