Side effects: LaunchedEffect and friends
Why it matters
LaunchedEffectandDisposableEffectare 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.
rememberUpdatedStateandderivedStateOfprevent two separate classes of bug: a long-running effect calling an old callback, and unnecessary recompositions from a calculated value.
The simple explanation
- A
LaunchedEffectis 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. DisposableEffectis like a subscription: you sign up when it starts, and you must cancel when you leave or switch plans.SideEffectis like updating the specials board after every finished round of cooking, so the front of house always sees the latest menu.rememberUpdatedStateis 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.
| API | When it runs | When it stops or cleans up |
|---|---|---|
LaunchedEffect(key1, key2, …) | Launches a coroutine when it enters the composition, and again when any key changes | The 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 changes | onDispose runs before a restart and when it leaves the composition |
SideEffect | After every successful composition and recomposition of the composable that calls it | No cleanup |
rememberUpdatedState(value) | Updates a remembered State with the latest value on every recomposition | Nothing to clean up |
derivedStateOf { … } | Recalculates when a state it reads changes | Notifies 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 emission | Stops 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 whenuserIdchanges and launches a new one. Cancellation is cooperative: suspending calls such asdelay,withContextandcollectstop with aCancellationException.DisposableEffectis for callback-style resources that need cleanup: registering aLifecycleObserver, a sensor listener or aBroadcastReceiver.SideEffectpushes 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.rememberUpdatedStateis for a value that changes across recompositions, typically a callback parameter, that a long-running effect must use without restarting. Aby remember { mutableStateOf(...) }variable does not need it: reading it inside the coroutine already gives the current value.derivedStateOfis for when inputs change more often than the result:listState.firstVisibleItemIndex > 0flips rarely while the index changes constantly.snapshotFlowturns state reads into a coldFlow. Collect it in a coroutine such as aLaunchedEffectto use operators likefilter,debounceordistinctUntilChangedon Compose state.
Notes
LaunchedEffect(key)cancels the previous coroutine whenkeychanges. Cancellation is cooperative:delay,withContextandcollectrespond to it. Blocking code such asThread.sleepdoes 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". DisposableEffectmust end with anonDispose { }block (the code does not compile without it). An emptyonDisposeis a smell: something was registered and never removed.SideEffectruns 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 aState<T>that always holds the latestvalue. Read it inside the long-running effect, usually withval current by rememberUpdatedState(onTimeout).derivedStateOf { … }must be wrapped inremember. It helps only when the result changes less often than its inputs.snapshotFlow { … }emits when the result of its block changes. Collect it inLaunchedEffectto 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 asonClick, which are not composable. UseLaunchedEffectfor 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
userIdchanges, the old coroutine is cancelled at its suspension point insidefetchUser, so it never writes its stale result. Notry/catchis needed for that; catchingCancellationExceptionand carrying on would be a bug. rememberUpdatedStateis used for the callback parameter, not forloading.loadingis Compose state, so reading it anywhere already gives the current value.LocalLifecycleOwner.currentis read in the composable body, outside the effect. Composable reads are not allowed insideonDisposeor 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
- 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.
- Short term: moved the call into
LaunchedEffect(userId), so it runs when the screen enters the composition and whenuserIdchanges. - Better: the ViewModel starts loading itself (in
init, from aSavedStateHandleid, or throughstateIn), so the composable only collects state. - Added a Compose UI test with a fake repository that forces several recompositions and asserts one request.
- LeakCanary reported a leaked settings screen object after users navigated away.
- The screen used
DisposableEffect(Unit)to add aLifecycleObserverto the Activity's lifecycle, butonDisposewas 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.
- Implemented
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }. - Changed the key from
UnittolifecycleOwner, 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 callcurrent(). - 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.
SideEffectruns after every successful recomposition, not just the first. For a one-time action useLaunchedEffect(Unit). - Using derivedStateOf when the result changes as often as its inputs. For
fullName = first + last, every input change changes the result, soderivedStateOfonly 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)
- Create a screen
DataScreen(itemId: Int, onLoaded: (String) -> Unit). - Add a
LaunchedEffect(itemId)that setsloading = true, calls a fake API (delay(1000)and then return a string), stores the result and setsloading = false. - Wrap the body of the effect in
try { ... } finally { Log.d("Data", "effect for $itemId ended") }. AddLog.dlines for "start" and "done" too. Do not catchCancellationException. - Read
onLoadedthroughval currentOnLoaded by rememberUpdatedState(onLoaded)and callcurrentOnLoaded(result)at the end of the effect. - Add a
DisposableEffect(Unit)that logs on enter and logs again inonDispose. - Run the app. Change
itemIdfrom 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". - Navigate away from the screen. Confirm the
onDisposelog 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.