--- name: state-and-background-footguns description: "Reactive state and background-work traps: StateFlow conflation, flatMapLatest, job lifecycles, ViewModel bases, WorkManager, backups, crash reporting, logging, Glance widgets. Use when state lags or flips, or work runs twice or never." --- # Reactive state and background work footguns 23 traps mined from a production Kotlin and Compose Multiplatform app, one short file each under `references/`. Every file gives the working pattern, the **Traps** (the specific ways it fails in practice, and why), and a **Verifying it** section with commands to run against the user's own tree. **How to use this index.** Match the code about to be written, or the symptom being chased, against the entries below: each names its topic and the symptom that should send you to it. Read every file that plausibly applies with the Read tool before proposing code or a fix; each is under 150 lines. Where a Verifying command names the source project's paths, substitute the equivalent paths in the user's tree. **Cross-references.** A backticked trap name inside a file that is not listed here lives in a sibling area skill: glob `../*/references/.md` to open it. ## Reactive state: Flow, StateFlow and ViewModel - [`stateflow-conflation-inverts-state`](references/stateflow-conflation-inverts-state.md) — A conflating state holder keeps one slot, so a callback that writes it several times per event makes write ORDER the correctness question — collectors see only the last write. Use when a spinner sits over content that is already loaded, when a loading flag clears at the wrong moment, or when a screen shows the state that was true one step ago. - [`named-job-lifecycle-discipline`](references/named-job-lifecycle-discipline.md) — One `var xJob: Job?` field per concern, cancel-before-relaunch as an invariant at every launch site, and teardown writes wrapped so a cancellation cannot stop them halfway. Use when periodic updates arrive several times per tick, when stale results from a previous item overwrite the current one, or when a long-lived object keeps working after it was released. - [`readonly-stateflow-cold-to-hot`](references/readonly-stateflow-cold-to-hot.md) — Expose state through `asStateFlow()` rather than an upcast of the mutable holder, and turn a cold source flow hot with `stateIn(scope, WhileSubscribed(timeout), initial)` so it survives collector churn without running forever. Use when a screen re-queries its source on every rotation or navigation, when work continues after the last collector leaves, or when something outside the owner is writing state it should only be reading. - [`flatmaplatest-resubscribe-composite-key`](references/flatmaplatest-resubscribe-composite-key.md) — Re-subscribe a downstream flow whenever a key flow changes using flatMapLatest, then collapse the resulting high-frequency stream to a composite key with distinctUntilChanged before firing expensive one-shot work. Use when a fetch re-runs on every progress tick, when it fires for the wrong item after a fast switch, or when a side effect never runs because one of its inputs arrives last. - [`distinct-by-key-reset-cancel-per-item`](references/distinct-by-key-reset-cancel-per-item.md) — Per-item pipelines that key on the item id with distinctUntilChangedBy, cancel the previous item's in-flight work before starting the next, and reset the visible state before filling it — so nothing from the previous item can appear under the new one. Use when a detail screen briefly shows the last item's artwork or text, when a slow response overwrites a newer one, or when a field stays populated after moving to an item that has no value for it. - [`combine-two-flags-to-gate`](references/combine-two-flags-to-gate.md) — Turn several independent condition flows into one on/off gate with `combine` + `distinctUntilChanged` + `collectLatest`, make both the start and the teardown branch idempotent, and run teardown uncancellably. Use when a subsystem starts before it is fully configured, keeps running after one of its preconditions is withdrawn, or ends up half-started after a fast toggle. - [`compose-multiplatform-viewmodel-base`](references/compose-multiplatform-viewmodel-base.md) — A shared ViewModel base class for Compose Multiplatform — container-aware so subclasses can pull extra dependencies without constructor threading, with one loading/error surface for every screen — and the blocking resource-lookup hazard that such a base almost always grows. Use when every screen is re-implementing its own loading dialog, when a base class needs a dependency only some subclasses use, or when app start stutters on the main thread before anything is drawn. - [`dual-mode-persist-blocking-or-async`](references/dual-mode-persist-blocking-or-async.md) — One suspend persistence body driven two ways — blocking on the shutdown path, where the write must complete before the scope dies, and fire-and-forget on periodic ticks — instead of two copies that drift apart. Use when saved state is correct while the app runs but wrong after a hard quit, when a teardown save silently does nothing, or when two save functions have grown different guards. - [`pending-state-makes-waiting-legible`](references/pending-state-makes-waiting-legible.md) — Model "asked, and not yet answered" as its own field, because without it a rejected request and a peer who simply has not looked at their screen are indistinguishable — both look like nothing happened. Covers the one set against many clears, clearing locally when no answer will ever come, and giving the user a way out. Use when an action appears to do nothing, when a screen can get stuck waiting forever, or when an error message has no place to appear. - [`preset-identity-read-back-from-value`](references/preset-identity-read-back-from-value.md) — Derive "which preset is this" by comparing the presets against the value in force instead of storing a label beside it, so editing drops to Custom by itself and returning re-selects — and derive any per-preset field that is a function of the preset's own numbers rather than writing it out per row. Use when a preset picker keeps showing a stale name, when a preset never re-selects itself, or when a per-row constant has drifted in one row out of twenty. - [`one-snapshot-per-period-not-many-flows`](references/one-snapshot-per-period-not-many-flows.md) — Return a whole period's figures as one immutable snapshot from a single suspend call, rather than as a dozen independent flows the screen has to line up — a screen comparing two spans needs each span coherent, and separate emissions let a count from this period render beside a total from the last. Covers when a single-emission flow is a suspend function in costume, which derived figures belong on the snapshot, and why a rate needs the denominator a human means. Use when a comparison screen briefly shows mismatched numbers while reloading, when adding the tenth flow to one screen's repository, or when two places compute the same average differently. - [`derive-the-flag-dont-store-and-correct-it`](references/derive-the-flag-dont-store-and-correct-it.md) — A boolean that is a pure function of state already being collected gets stored as its own `mutableStateOf` anyway, seeded with a guess and corrected a frame later by a `LaunchedEffect` — so the first frame renders the guess, and later changing only the seed value does nothing once `rememberSaveable` has already saved the old one. Use when a UI element visibly flashes shown-then-hidden-then-shown on cold start, or when editing a `remember`/`rememberSaveable` initializer doesn't change what a warm app already shows. ## Background work, services and platform runtime - [`app-backup-to-zip-mediastore`](references/app-backup-to-zip-mediastore.md) — Back an app up into one zip that lands in the user's own Downloads folder with no storage permission, keeping only the newest N archives. Covers checkpointing the database's write-ahead log before the file is copied, assembling the archive in cache first, inserting through the system media store, and pruning old archives with a query over that same collection. Android only. Use when a restored backup is missing the most recent writes, when the backup file is invisible to the user's file manager, or when old backups accumulate forever. - [`datastore-driven-workmanager`](references/datastore-driven-workmanager.md) — Drive periodic background work straight from the settings store, so a toggle or an interval change takes effect immediately without a restart. Covers combining several preference flows into one scheduling decision, the update-in-place enqueue policy that lets a changed interval actually change, cancelling by unique name on disable, and why the worker must re-read the same settings itself. Android only. Use when changing a backup or sync interval does nothing until reinstall, when work keeps running after the user turned it off, or when two schedules end up stacked. - [`periodic-worker-dedup`](references/periodic-worker-dedup.md) — Build a periodic notifier that never misses an item when a run is delayed, and whose only way to repeat one is a kill inside a single narrow window. Covers keeping the "already handled" record in the database rather than in the worker, scanning a time window deliberately wider than the scheduling interval so a skipped run catches up, and processing oldest-first so an interrupted run loses the newest item rather than a random slice. Android only. Use when users report duplicate notifications after a device restart, when items are missed while the device is idle, or when a first run floods the user with the whole back catalogue. - [`desktop-single-instance-before-di`](references/desktop-single-instance-before-di.md) — Order a desktop app's startup so the single-instance guard runs before the dependency container and before anything opens on-disk state. Covers forwarding a second launch's arguments to the running instance and exiting, bridging a restore request from outside the UI framework into the live window, and the platforms where a second launch never produces a second process at all. Use when launching the app a second time crashes or corrupts settings, when a link opened while the app is running does nothing, or when the second window steals a file the first one owns. - [`compose-desktop-runtime-hardening`](references/compose-desktop-runtime-hardening.md) — The ordered list of probes, system properties and platform gates a Compose desktop entry point must run before its first window exists. Covers warming the JDK's desktop-integration API ahead of any native load, renderer and interop properties that are read once at start-up, turning off vsync where the wait can park the UI thread, gating transparency and a custom titlebar on virtual-machine detection, and setting the Linux window-class name reflectively so the desktop entry binds. Use when the UI freezes while audio keeps playing after moving the window to another monitor, when the window never appears in a virtual machine, or when the Linux dock shows a class name instead of your app. - [`swappable-crash-reporting-and-dialog`](references/swappable-crash-reporting-and-dialog.md) — Ship a build with crash reporting and a build with none from one codebase, by swapping a module that exposes three top-level functions instead of an interface, so call sites are byte-identical and the no-tracking build provably contains no reporting code. Also covers a desktop crash dialog built on the older widget toolkit, because the modern UI may be exactly what just died, and how to marshal it onto that toolkit's event thread. Use when a privacy build must contain no reporting dependency at all, when a swapped implementation is drifting from its counterpart, or when the app dies with no visible error and no way for a user to send you the details. - [`kmp-logger-facade`](references/kmp-logger-facade.md) — Put one small logging object in the shared module between every call site and the logging library, so a chatty subsystem can be silenced in one line and the library can be replaced without touching call sites. Covers the muted-tag set, a level-as-a-value enum for callers that pick severity at runtime, and why a single direct import of the library anywhere defeats both. Use when one subsystem drowns the log, when swapping or upgrading a logging library means editing hundreds of files, or when muting a tag has no effect on some of its output. - [`glance-widget-over-existing-state`](references/glance-widget-over-existing-state.md) — Build a home-screen widget that renders the app's existing state holder rather than a parallel copy of it, by injecting the same shared state object and the same long-lived scope the app already uses and re-issuing the widget update whenever that state changes. Covers dispatching the app's own UI events from widget buttons, why the injection target must be a singleton rather than a screen-scoped definition, making the whole widget a tap target, turning off hardware bitmaps for artwork the widget must read, and the leak to avoid when starting those collectors from the widget's provide-glance callback. Android only. Use when a widget shows stale playback or session state, when its artwork is blank, when a tap on it opens the launcher's menu or does nothing at all, or when its buttons need their own duplicate logic. - [`remoteviews-bitmap-budget`](references/remoteviews-bitmap-budget.md) — Every bitmap a home-screen widget draws is copied into the RemoteViews payload handed across a process boundary, and the platform rejects an update whose bitmaps exceed a fixed budget — so decoding each image at the size it is drawn is not an optimisation, it is what keeps the widget on screen. Covers the pixel arithmetic that decides how many images fit, why the failure is invisible outside the system log, and why every surface reading the same image must agree on both its cache key and its decode size. Android only. Use when a widget shows the framework's error placeholder, when it renders on one device and not another, or when adding one more tile empties the whole widget. - [`glance-layout-vocabulary`](references/glance-layout-vocabulary.md) — The composable widget toolkit is not Compose with a different import — it has no aspect ratio, its weight is always 1 so an even split is the entire vocabulary, its corner radius only applies from API 31, and a widget always fills the launcher's cell so the spare height must be spent deliberately. Covers the weighted-spacer trick that keeps square tiles square, and where a fill modifier swallows a whole band. Android only. Use when a square tile renders as a rectangle, when a widget shows a block of dead colour below its content, or when corners are round on one device and square on another. - [`on-demand-dictionary-asset`](references/on-demand-dictionary-asset.md) — A tokenizer, spellchecker or analyzer needs a multi-megabyte dictionary that would bloat every install for a feature most users leave off — fetch it once, on opt-in, into a plain directory, and make every consumer ask the filesystem "am I ready" rather than trust a flag. Use when a per-language asset inflates a package on only one target, when a half-downloaded asset must never look installed, or when a feature stays broken even after its download reports success.