android-kotlin-concurrency
Skill3 starsChanged 7 months agoMITView on GitHub
Kotlin coroutines and Flow engineering skill for structured concurrency, scope lifecycle, dispatcher strategy, and reactive stream design. Use when coroutine leaks, cancellation failures, dispatcher misuse, Flow vs StateFlow selection, or thread-safety in suspend functions are in scope.
In this repository11 other files it gives its agents.
- AGENTS.mdAGENTS.md
- android-engineering-skillSkill
- android-architectureSkill
- android-code-reviewSkill
- android-composeSkill
- android-debuggingSkill
- android-gradle-buildSkill
- android-performanceSkill
- android-release-engineeringSkill
- android-securitySkill
- android-testingSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
24 rules. About 0 are common, 5 are distinctive, and 19 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
19
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 37
when the primary question is ViewModel architecture or repository layering (android-architecture)
- Very specific: line 38
when the primary question is jank or startup profiling without concurrency root cause (android-performance)
- Very specific: line 39
when the question is Compose state management specifically (android-compose)
- Distinctive: line 47
Run cross-skill checks (architecture for ownership, performance for hot-path impact).
- Very specific: line 56
use viewModelScope — auto-cancelled on ViewModel cleared.
- Very specific: line 57
do not use GlobalScope or manually constructed scopes that outlive the ViewModel.
- Very specific: line 59
use lifecycleScope with repeatOnLifecycle for Flow collection.
- Very specific: line 60
avoid launchWhenStarted — it suspends but does not cancel on STOP.
- Very specific: line 63
never create ad-hoc CoroutineScope(Dispatchers.IO) without a cancellation owner.
- Very specific: line 65
use CoroutineWorker or bind to an injected scope with explicit job cancellation.
- Very specific: line 82
Do not apply withContext(Dispatchers.IO) as a blanket jank fix — profile before changing dispatcher.
- Very specific: line 87
Use withTimeout / withTimeoutOrNull for deadline-bound operations.
- Very specific: line 88
Avoid swallowing CancellationException in try/catch (e: Exception) blocks — always re-throw it.
- Very specific: line 89
Prefer supervisorScope when child failure must not cancel siblings.
- Very specific: line 93
Use StandardTestDispatcher with advanceUntilIdle() for deterministic coroutine control.
- Very specific: line 95
Use turbine for Flow assertion in unit tests.
- Distinctive: line 100
When used with other skills:
- Very specific: line 113
Use measurable gates and label each pass | at-risk | fail:
- Very specific: line 118
test determinism gate: all coroutine tests use injected test dispatcher.
- Distinctive: line 120
If no observable evidence exists, return a measurement and instrumentation plan before recommending dispatcher or scope changes.
- Distinctive: line 130
Do not present temporary concurrency shortcuts as final architecture.
- Distinctive: line 140
If confidence is medium/low:
- Very specific: line 149
Use the standard payload defined in ../../AGENTS.md (section: Cross-skill handoff contract).
- Very specific: line 154
Follow global order from ../../AGENTS.md:
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Purpose
Design correct and leak-free Kotlin concurrency in Android using structured concurrency principles, evidence-driven dispatcher strategy, and safe reactive stream composition.
Scope and authority
This skill is lead authority for:
- coroutine scope design and lifecycle binding
- Flow / StateFlow / SharedFlow selection and composition
- dispatcher strategy and thread-safety decisions
- cancellation safety and structured concurrency enforcement
- suspend function design and cold/hot stream selection
This skill must defer when applicable:
- architectural ownership of ViewModels and repositories to
android-architecture - UI state rendering and recomposition to
android-compose - performance profiling and ANR root-cause to
android-performance
When to use
- coroutine scope is leaking or outliving its lifecycle (e.g.,
GlobalScopemisuse) - cancellation is not propagating correctly across suspend calls
FlowvsStateFlowvsSharedFlowselection is unclear or wrong- dispatcher choice causes jank or blocks the main thread
- suspend function is not cancellable or has unsafe shared mutable state
- structured concurrency violations in production or test code
When not to use
- when the primary question is ViewModel architecture or repository layering (
android-architecture) - when the primary question is jank or startup profiling without concurrency root cause (
android-performance) - when the question is Compose state management specifically (
android-compose)
Decision engine workflow
- Identify the concurrency problem class (scope, dispatcher, cancellation, stream type, thread-safety).
- Classify lifecycle binding context (ViewModel, Fragment, Service, WorkManager, standalone).
- Select stream type and scope strategy branch.
- Validate dispatcher choice and cancellation propagation.
- Run cross-skill checks (architecture for ownership, performance for hot-path impact).
- Resolve conflicts using authority model from
../../AGENTS.md. - Return implementation guidance with fallback options.
Branching decision tree
Branch A: scope and lifecycle binding
ViewModel(UI-triggered async work):- use
viewModelScope— auto-cancelled on ViewModel cleared. - do not use
GlobalScopeor manually constructed scopes that outlive the ViewModel.
- use
Fragment / Activity(lifecycle-bound observation):- use
lifecycleScopewithrepeatOnLifecyclefor Flow collection. - avoid
launchWhenStarted— it suspends but does not cancel on STOP.
- use
Repository / data layer(no lifecycle):- inject a
CoroutineScopefrom DI with explicit ownership. - never create ad-hoc
CoroutineScope(Dispatchers.IO)without a cancellation owner.
- inject a
WorkManager / Service:- use
CoroutineWorkeror bind to an injected scope with explicit job cancellation.
- use
Branch B: stream type selection
StateFlow: current-value holder for UI state; always has a value; replays last to new collectors.SharedFlow: for events/effects that must not replay (navigation events, one-time signals).Flow(cold): on-demand data streams (Room queries, network, Paging); no independent lifecycle.Channel: only when one-to-one producer-consumer delivery with backpressure is required; preferFlowotherwise.
Branch C: dispatcher strategy
Dispatchers.Main: UI updates, StateFlow emissions from ViewModel, navigation triggers.Dispatchers.Main.immediate: when already on main thread and dispatch overhead must be avoided.Dispatchers.IO: blocking I/O (network, disk, database). Not for CPU-intensive work.Dispatchers.Default: CPU-intensive computation (parsing, sorting, encoding).Dispatchers.Unconfined: avoid in production; use only in tests withUnconfinedTestDispatcher.
Do not apply withContext(Dispatchers.IO) as a blanket jank fix — profile before changing dispatcher.
Branch D: cancellation safety
- Long-running suspend loops must call
ensureActive()or checkisActiveat iteration boundaries. - Use
withTimeout/withTimeoutOrNullfor deadline-bound operations. - Avoid swallowing
CancellationExceptionintry/catch (e: Exception)blocks — always re-throw it. - Prefer
supervisorScopewhen child failure must not cancel siblings.
Branch E: testing strategy
- Use
StandardTestDispatcherwithadvanceUntilIdle()for deterministic coroutine control. - Inject dispatchers via constructor — never hardcode
Dispatchers.IOin production classes. - Use
turbinefor Flow assertion in unit tests. - Replace
delay()with virtual time in tests viaTestCoroutineScheduler.
Conflict handling and composition
When used with other skills:
- With
android-architecture:- scope ownership must align with layer ownership; a Repository must not own a ViewModel-scoped job.
- With
android-performance:- measured jank may implicate wrong dispatcher; escalate with trace evidence before changing dispatch strategy.
- With
android-testing:- flaky tests caused by real-time delays or shared coroutine state require deterministic dispatcher injection.
- With
android-compose:StateFlowconsumed in Compose must be collected withcollectAsStateWithLifecycle, notcollectAsState.
Quantitative gates
Use measurable gates and label each pass | at-risk | fail:
- scope-leak gate: no coroutines alive after owning lifecycle ends (verified by leak detection or test)
- cancellation propagation gate:
CancellationExceptionreaches structured root without suppression - dispatcher correctness gate: no blocking calls on
Dispatchers.Main; no UI updates fromDispatchers.IO - test determinism gate: all coroutine tests use injected test dispatcher; no
Thread.sleep()or realdelay()
If no observable evidence exists, return a measurement and instrumentation plan before recommending dispatcher or scope changes.
Tradeoff realism
Allow context-justified non-ideal decisions when explicit:
GlobalScopemay be acceptable for fire-and-forget analytics with no cancellation requirement — must be labeled.runBlockingis acceptable in tests and top-level entry points; never acceptable in production suspend chains.- Mixing cold Flow and SharedFlow is acceptable during migration with an explicit cutover plan.
Do not present temporary concurrency shortcuts as final architecture.
Uncertainty protocol
Always report confidence:
High(>= 0.80)Medium(0.60-0.79)Low(< 0.60)
If confidence is medium/low:
- state missing context (scope ownership, lifecycle binding, whether caller is suspend or not)
- provide at least one conservative fallback
- escalate to
android-architecturewhen scope ownership is structurally ambiguous - escalate to
android-performancewhen dispatcher change is proposed without profiling evidence
Cross-skill handoff payload
Use the standard payload defined in ../../AGENTS.md (section: Cross-skill handoff contract).
Set requesting_skill to android-kotlin-concurrency.
Output contract
Follow global order from ../../AGENTS.md:
Context and constraintsDecision and rationaleAlternatives consideredTradeoffsRisks and mitigationsConfidence and unknownsCross-skill impactsNext implementation steps
Also include:
Scope and lifecycle binding strategyStream type selectionDispatcher strategyCancellation safety analysisTesting approach
Anti-pattern detection
GlobalScopeusage without explicit fire-and-forget justificationlaunchWhenStartedfor Flow collection (suspends but does not cancel)- blocking calls (
Thread.sleep,runBlocking) inside suspend functions or coroutines - catching
CancellationExceptionwithout re-throwing - hardcoded
Dispatchers.IOin production classes without injection SharedFlowused for UI state that needs a current value (useStateFlowinstead)- missing
repeatOnLifecyclefor lifecycle-aware Flow collection in UI layer
Related resources
references/kotlin-concurrency-patterns.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

