A decision guide for choosing the right side-effect API, knowing when keys matter, and understanding how stale-closure bugs sneak into production.
Most Compose bugs that survive code review share one trait: the code looks correct when read top to bottom, but it is executed under rules the author did not have in mind. Side effects are the sharpest example. This post walks through each effect API, the specific way each one fails in a real app, and a quick way to choose between them.
1. Why composables must be side-effect free
A composable function is closer to a draft than a transaction. The runtime is free to:
-
Run it often. Reading snapshot-backed state (
State<T>,mutableStateOf,SnapshotStateList) in the body subscribes that recompose scope to changes. A plainvaror a regular object does not. During an animation, that can mean once per frame. - Run siblings in any order. Never rely on one composable having executed before another.
- Skip it. A restartable composable whose inputs are unchanged (and stable, or covered by strong skipping, the default in Kotlin 2.0.20+) is skipped unless a snapshot state it read has changed. Anything you hid inside the body silently does not happen.
- Discard a pass. A composition can be abandoned before it is committed. Work done during that pass was real; the UI it described never appeared.
Here is the kind of code this rule is meant to prevent:
@Composable
fun CartBadge(count: Int, analytics: Analytics) {
analytics.log("cart_badge_shown", count) // fires on every recomposition
Badge { Text(count.toString()) }
}
In a dashboard this looks like an “impression” metric that is inflated by 20x, because the badge recomposes whenever any parent state changes. Worse, a discarded composition still logs. The fix is not to log “less”. The fix is to move the work to an API that is tied to the committed composition:
@Composable
fun CartBadge(count: Int, analytics: Analytics) {
LaunchedEffect(count) {
analytics.log("cart_badge_shown", count)
}
Badge { Text(count.toString()) }
}
The rest of this post is about picking which of those APIs, and keying it correctly.
2. LaunchedEffect(key): restart semantics and the Unit/true anti-pattern
LaunchedEffect launches a coroutine once the composition that contains it has been committed (not during the composition pass itself). When any key changes, the running coroutine is cancelled and a new one is launched with the new key values. When the call site leaves the composition, the coroutine is cancelled for good. Keys are compared with equals.
@Composable
fun ParcelTrackingScreen(
parcelId: String,
viewModel: TrackingViewModel = hiltViewModel(),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
LaunchedEffect(parcelId) {
viewModel.startTracking(parcelId)
}
TrackingContent(state)
}
The Unit / true anti-pattern
LaunchedEffect(Unit) and LaunchedEffect(true) mean "run once, never restart". That is a legitimate choice only when the block depends on nothing that can change. The failure mode appears when a developer reaches for Unit just to silence the key question:
// Looks fine in a demo. In production, parcelId changes via deep link or
// bottom-nav reselect, and tracking keeps following the old parcel.
LaunchedEffect(Unit) {
viewModel.startTracking(parcelId)
}
Nothing crashes. The screen simply shows data for the wrong parcel, and the bug only reproduces when navigation reuses the same composable instance with a new argument.
Rule of thumb: every value your block reads and that can change is either a key or is read through rememberUpdatedState (section 7). If you genuinely have neither, Unit is fine, but say why in a comment.
The opposite failure: keys that are too wide
// uiState is a new object on every location tick
LaunchedEffect(uiState) {
viewModel.startTracking(uiState.parcelId) // restarts constantly
}
Here the effect restarts on every emission, resubscribing to a stream and flickering loading indicators. Key on the narrowest value the block needs:
LaunchedEffect(uiState.parcelId) { viewModel.startTracking(uiState.parcelId) }
Two more traps worth a code-review reflex:
-
Lambdas as keys restart the effect whenever the lambda instance changes. Strong skipping memoizes lambdas created inside composables, keyed on what they capture, so this is less common than it used to be. Lambdas built outside composition (a factory, a ViewModel) or compiled without strong skipping can still be new on every recomposition, and a capturing lambda legitimately changes when its captures change. Treat a lambda key as fragile and prefer
rememberUpdatedState(section 7). - Mutable collections as keys can compare equal after mutation and fail to restart. Prefer immutable values.
3. rememberCoroutineScope for event handlers
LaunchedEffect reacts to composition. A click is not a composition event, so it cannot start a LaunchedEffect. For work triggered by callbacks, rememberCoroutineScope gives you a scope bound to the call site's lifetime:
@Composable
fun ReorderButton(
orderId: String,
snackbarHostState: SnackbarHostState,
reorder: suspend (String) -> Result<Unit>,
) {
val scope = rememberCoroutineScope()
var inFlight by remember { mutableStateOf(false) }
Button(
enabled = !inFlight,
onClick = {
scope.launch {
inFlight = true
try {
val message = if (reorder(orderId).isSuccess) "Order placed again" else "Could not reorder"
snackbarHostState.showSnackbar(message)
} finally {
inFlight = false
}
}
},
) { Text("Reorder") }
}
Failure modes to know:
-
Launching in the body.
scope.launch { ... }written directly inside a composable runs on every recomposition. If you find yourself doing this, you wantedLaunchedEffect. -
Work that must outlive the screen. The scope is cancelled when the composable leaves the composition. A rotation, a back press, or a navigation transition can cancel a purchase call halfway. Anything that must complete belongs in a
ViewModel(or an application-scoped component), with the UI only requesting it. -
Swallowing cancellation. Wrapping a suspend call in
runCatchingcatchesCancellationException, and the coroutine keeps going after it has been cancelled. Rethrow it, or catch narrower types. -
Double taps. Each click launches a new coroutine. Disable the control, as above, or cancel the previous
Job. -
Uncaught exceptions. A scope from
rememberCoroutineScopehas noCoroutineExceptionHandler, so a thrown exception fromscope.launchcan crash the app. That is whyreorderabove returns aResultinstead of throwing; if your suspend function throws, catch the specific exceptions you expect.
4. DisposableEffect: registering and cleaning up listeners and observers
Use DisposableEffect when the setup has a matching teardown and is not naturally a suspend function: lifecycle observers, system callbacks, broadcast receivers, OnBackPressedCallback, sensor listeners. The onDispose block is mandatory and runs both when the key changes and when the call site leaves the composition.
@Composable
fun ScannerLifecycleEffect(scanner: BarcodeScanner) {
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner, scanner) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_START -> scanner.start()
Lifecycle.Event.ON_STOP -> scanner.stop()
else -> Unit
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
scanner.stop()
}
}
}
(LocalLifecycleOwner now lives in the androidx.lifecycle.compose package, shipped in the androidx.lifecycle:lifecycle-runtime-compose artifact from lifecycle 2.8.0. Older code imports it from androidx.compose.ui.platform.)
Shortcut for the common case. If all you need is “do X on start, undo on stop” (or resume/pause), recent lifecycle-runtime-compose releases provide LifecycleStartEffect and LifecycleResumeEffect, which wrap this observer boilerplate. The hand-written version above is still the right tool when you need other lifecycle events or non-lifecycle registrations.
Failure modes:
-
Missing a key. If
scannerwere not a key and the parent swapped scanner instances, the observer would keep driving the old scanner while the new one sat idle, and the old camera handle would leak. -
Wrong thread. Some system callbacks (for example,
ConnectivityManager.NetworkCallback) are delivered off the main thread. Writing snapshot state from there is permitted, but read-modify-write sequences are still racy without your own synchronization, and touching views or calling main-only APIs is not allowed. -
Cleanup that throws. An exception in
onDisposecan abort teardown of later effects. Keep it small and defensive. -
Ordering assumptions. On a key change, the old
onDisposeruns before the new effect block. Do not assume the resources overlap.
5. SideEffect: publishing Compose state to non-Compose code
SideEffect runs after every successful recomposition of the scope it lives in, during the apply phase on the applying thread (the main thread on Android), and never for a discarded pass. That makes it the right place to mirror Compose state into an object that Compose does not own.
@Composable
fun CheckoutScreen(step: CheckoutStep, crashContext: CrashContext) {
SideEffect {
crashContext.setCustomKey("checkout_step", step.name)
}
CheckoutContent(step)
}
The mental model is “keep an external value in sync with what is currently on screen”. Because it runs so often, it must be cheap and idempotent.
Failure modes:
-
Non-idempotent work.
SideEffect { retryCount++ }increments on every recomposition, not once per meaningful change. -
Launching coroutines inside it. This starts a new coroutine per recomposition. Use
LaunchedEffect. - Heavy work. Disk or network calls here run on the main thread, repeatedly.
-
Expecting cleanup. There is none. If you need to undo the publication, use
DisposableEffect. -
Wrapping view updates. When bridging a classic
View, theupdatelambda ofAndroidViewis designed for this and is a better home.
6. produceState, snapshotFlow, derivedStateOf
These three are not side effects in the same sense. They convert between worlds: non-Compose to state, state to Flow, and state to state.
produceState: turn an async source into State
sealed interface Loadable<out T> {
data object Loading : Loadable<Nothing>
data class Ready<T>(val value: T) : Loadable<T>
data class Failed(val cause: Throwable) : Loadable<Nothing>
}
@Composable
fun rememberStoreHours(
storeId: String,
repo: StoreRepository,
): State<Loadable<StoreHours>> =
produceState<Loadable<StoreHours>>(initialValue = Loadable.Loading, storeId, repo) {
value = try {
Loadable.Ready(repo.hours(storeId))
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
Loadable.Failed(e)
}
}
It is a LaunchedEffect plus a remembered MutableState with the same key semantics. Failure mode: forgetting storeId as a key, which shows hours for a store you already left.
snapshotFlow: observe Compose state as a Flow
@Composable
fun FeedScrollTelemetry(listState: LazyListState, tracker: FeedTracker) {
val currentTracker by rememberUpdatedState(tracker)
LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemIndex }
.collect { index -> currentTracker.onFirstVisibleChanged(index) }
}
}
snapshotFlow re-evaluates its block whenever a state object it read changes. It is the bridge for operators like debounce and combine that you cannot apply to raw State. Failure mode: the block captures a plain parameter (not state), so later changes never reach it. Read it via rememberUpdatedState as above, or make it a key of the surrounding LaunchedEffect.
derivedStateOf: cache a value computed from state
val showJumpToTop by remember {
derivedStateOf { listState.firstVisibleItemIndex > 5 }
}
The input changes on nearly every scroll frame; the output flips rarely, so readers recompose only on the flip.
Failure modes:
-
Non-state inputs. If the calculation uses a plain parameter, the cached lambda captures the first value forever. Pass it to
remember:
val isOverLimit by remember(limit) { derivedStateOf { items.size > limit } }
-
No reduction in changes. If the output changes as often as the input,
derivedStateOfis pure overhead. Compute it inline.
7. The stale lambda problem and rememberUpdatedState
A coroutine started in LaunchedEffect is a closure. It captures values at launch. If the effect lives longer than one composition, and it calls a lambda or reads a parameter that the caller later replaces, the closure still holds the original.
@Composable
fun SessionExpiryGuard(ttl: Duration, onExpired: () -> Unit) {
LaunchedEffect(ttl) {
delay(ttl)
onExpired() // which onExpired? the one from the launch composition
}
}
Suppose the caller’s onExpired clears the cart whose id is cartId, and the user switches carts while the timer runs. The timer fires, and the old lambda clears the old cart. No exception, no log line, just a quiet data bug.
You have three options:
- Add the lambda as a key. The timer restarts whenever the lambda instance changes. If the caller’s lambda changes often (for example, its captured values change), the session may never expire. Wrong for timers.
-
Leave it out (
Unit). Stale, as above. -
Read it through a
Stateholder. The effect keeps running, but the value it reads is current.
@Composable
fun SessionExpiryGuard(ttl: Duration, onExpired: () -> Unit) {
val currentOnExpired by rememberUpdatedState(onExpired)
LaunchedEffect(ttl) {
delay(ttl)
currentOnExpired()
}
}
rememberUpdatedState creates one State object that survives recomposition and has its .value overwritten with the latest argument. The coroutine captured the holder, so the read at fire time sees the newest lambda.
Two clarifications that come up in review:
- Strong skipping does not solve this. The compiler may remember lambdas for you, which affects recomposition skipping. It does not change what a long-running coroutine captured.
-
The same pattern applies beyond
LaunchedEffect. Use it forDisposableEffectcallbacks (as in the connectivity and scanner examples) and forsnapshotFlowcollectors.
The test for when to use it: “Is this effect long-lived, and does it read something the caller can change, where I do not want a restart?” If yes, use rememberUpdatedState. If a restart is the correct behavior, make it a key.
8. Scenario → API
A few heuristics that cover most review comments:
-
Triggered by composition or a changing value?
LaunchedEffect, keyed on what the block reads. -
Triggered by a user action?
rememberCoroutineScope, and push anything that must survive navigation into theViewModel. -
Has an “undo” step?
DisposableEffect. If you wrote "unregister", "close" or "stop" in your head, it belongs here. -
Just telling a non-Compose object what is on screen?
SideEffect, cheap and idempotent. -
Need a value, not an action?
produceState(async source),derivedStateOf(computed from state), orsnapshotFlow(stream of state). -
Long-lived effect, changing input, no restart wanted?
rememberUpdatedState.
A short pre-merge checklist
- Does any composable body call a repository, logger, or listener registration directly?
- For each
LaunchedEffect/DisposableEffect/produceState: can I list every value the block reads, and is each one a key or read throughrememberUpdatedState? - Does every
LaunchedEffect(Unit)have a reason that a reviewer can read? - Is anything launched from
rememberCoroutineScopesomething the user would be upset to lose on rotation? - Does every
catch (e: Exception)around suspend code rethrowCancellationException?
Effects are where declarative UI meets the imperative world. Choose the API by what triggers the work and what has to be undone, key it by what the work reads, and the stale-closure and double-fire bugs mostly disappear before they ship.
Appendix: supporting declarations and imports
The snippets above focus on the effect APIs. To compile them, you need the declarations and dependencies below. The types are minimal stand-ins for your own.
Dependencies (versions illustrative; use your project’s catalog):
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7") // collectAsStateWithLifecycle, LocalLifecycleOwner
implementation("androidx.hilt:hilt-navigation-compose:1.2.0") // hiltViewModel()
implementation("androidx.compose.material3:material3") // Badge, Button, SnackbarHostState
Stand-in types:
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.StateFlow
import java.io.IOException
interface Analytics { fun log(event: String, value: Int) }
data class TrackingUiState(val parcelId: String = "")
abstract class TrackingViewModel : ViewModel() {
abstract val uiState: StateFlow<TrackingUiState>
abstract fun startTracking(parcelId: String)
}
interface BarcodeScanner { fun start(); fun stop() }
interface CrashContext { fun setCustomKey(key: String, value: String) }
interface FeedTracker { fun onFirstVisibleChanged(index: Int) }
enum class CheckoutStep { Cart, Address, Payment, Review }
data class StoreHours(val opens: String, val closes: String)
interface StoreRepository {
@Throws(IOException::class)
suspend fun hours(storeId: String): StoreHours // must be suspend
}
Imports commonly missed:
import androidx.compose.runtime.*
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.time.Duration
delay(Duration) is the kotlinx.coroutines overload; without that import, delay(ttl) will not resolve for a Duration argument. TrackingContent and CheckoutContent are your own UI composables.
🔐 Go Beyond Using Android — Master How It’s Actually Secured
If you’re building, testing, or breaking Android apps, understanding the security model beneath the SDK separates developers who follow best practices from those who truly understand why those practices exist. I highly recommend “Mastering Android Security: From Fundamentals to Advanced Practice.” It’s a comprehensive, architecture-first journey through app sandboxing, cryptography, network defense, reverse engineering, and exploitation — spanning everything from AndroidManifest.xml internals to TrustZone and the Verified Boot chain, with hands-on labs at every step.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover
Originally published on Medium.




Top comments (0)