/engsys-kotlin:kotlin-coroutinesfrom engsys-kotlin
Write data-safe asynchronous Kotlin with coroutines, Flow, and structured concurrency on Android. Use when fixing coroutine cancellation or leak bugs, choosing dispatchers (Default/IO/Main), designing suspend functions, modeling streams with Flow/StateFlow/SharedFlow, scoping work to viewModelScope/lifecycleScope, handling exceptions with CoroutineExceptionHandler/supervisorScope, or converting callback/RxJava APIs to coroutines. Covers Kotlin 2.x, kotlinx.coroutines structured concurrency discipline, and the Android main-safety contract.
Ships in engsys-kotlin. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Review, fix, and write concurrent Kotlin targeting Kotlin 2.1+ and kotlinx.coroutines 1.9+. Apply structured concurrency, correct dispatcher choice, and cooperative cancellation with minimal behavior changes. This is the Kotlin equivalent of Swift's structured-concurrency discipline: scopes are the unit of lifetime, cancellation is cooperative, and main-safety is non-negotiable.
When diagnosing a coroutine issue, follow this sequence:
viewModelScope, lifecycleScope,
a custom CoroutineScope, or an unscoped GlobalScope — a red flag).CancellationException (normal) or
a real failure.| Situation | Recommended fix |
|---|---|
| Work tied to a screen | Launch in viewModelScope; never GlobalScope. |
| Blocking IO (disk, network, DB) | withContext(Dispatchers.IO) { ... }. |
| Heavy CPU work (parse, sort, image) | withContext(Dispatchers.Default) { ... }. |
| UI / state update | Stay on Dispatchers.Main (the default for viewModelScope). |
| One child failure must not kill siblings | Use supervisorScope / SupervisorJob. |
| Long loop never cancels | Add ensureActive() / yield() or use cancellable APIs. |
| Callback API | Wrap with suspendCancellableCoroutine or callbackFlow. |
CancellationException
is never caught-and-ignored.Every coroutine has a parent. A parent does not complete until all children complete; cancelling a parent cancels all children. This is the core safety guarantee — never break out of it.
coroutineScope { } to launch concurrent children that all must finish
before the function returns.async/await for concurrent work that produces values.launch for fire-and-forget work within a scope (not detached).suspend fun loadDashboard(): Dashboard = coroutineScope {
val profile = async { repo.profile() } // runs concurrently
val feed = async { repo.feed() } // runs concurrently
Dashboard(profile.await(), feed.await()) // both joined here
}
If either child throws, the scope cancels the sibling and rethrows — no leaks.
Never use GlobalScope.launch. It has no parent, no lifecycle, no
cancellation. It is the coroutine equivalent of a detached, unowned thread.
| Scope | Lifecycle | Use for |
|---|---|---|
viewModelScope | Cleared when the ViewModel clears | All ViewModel async work |
lifecycleScope | Tied to a Lifecycle (Activity/Fragment) | UI-layer work bound to a screen |
rememberCoroutineScope() | Tied to a composable's lifetime | Launching from Compose event callbacks |
custom CoroutineScope | You manage cancel() | Long-lived components (cancel explicitly) |
For a custom scope, always pair a SupervisorJob with a dispatcher and cancel it
when the owner is destroyed:
class Connection {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
fun close() = scope.cancel() // cancels all children — no leaks
}
In Compose, collect with collectAsStateWithLifecycle() (not collectAsState())
so collection stops when the app is in the background.
A suspend function should be main-safe: callable from the main thread without blocking it. Push the thread switch down into the function, not up to callers.
Dispatchers.Main — UI updates. The default for viewModelScope.Dispatchers.Default — CPU-bound work (parsing, sorting, image processing).
Backed by a pool sized to CPU cores.Dispatchers.IO — blocking IO (disk, network sockets, JDBC, file). Backed by
a large elastic pool.Dispatchers.Main.immediate — runs inline if already on the main thread,
avoiding an unnecessary re-dispatch (use for state emission).// Main-safe: caller can invoke from the main thread.
suspend fun parseLargeJson(raw: String): Model = withContext(Dispatchers.Default) {
json.decodeFromString(raw)
}
Rules:
Thread.sleep, blocking network, runBlocking).withContext, not launch, to switch dispatchers for a value-returning
step — withContext returns to the original dispatcher when done.CoroutineDispatcher provider) so tests can substitute
StandardTestDispatcher.Cancellation is cooperative. A coroutine only stops at a suspension point or when it checks cooperatively.
suspend fun process(items: List<Item>) {
for (item in items) {
ensureActive() // throws CancellationException if cancelled
heavyWork(item) // CPU loops won't cancel on their own
}
}
delay, withContext, Flow
operators) are cancellable automatically.ensureActive() or yield().CancellationException is special: it signals normal cancellation. Never catch
it and swallow it. If you catch Exception broadly, rethrow it:try {
risky()
} catch (e: CancellationException) {
throw e // must rethrow — never swallow
} catch (e: Exception) {
handle(e)
}
withContext(NonCancellable) { ... } inside a finally.coroutineScope / async, exceptions propagate to the awaiting caller —
handle with try/catch around await().launch, an uncaught exception propagates up and cancels the scope. Install
a CoroutineExceptionHandler on the root scope for last-resort handling.supervisorScope / SupervisorJob isolate child failures so one failing child
does not cancel its siblings:supervisorScope {
launch { mightFail() } // failure here does NOT cancel the sibling
launch { mustSucceed() }
}
CoroutineExceptionHandler only works on root launch coroutines, never on
async (whose exception surfaces at await).Flow<T> is a cold asynchronous stream — it does nothing until collected, and
re-runs its producer for each collector. It is the Kotlin analogue of an
AsyncSequence.
fun searchResults(query: String): Flow<List<Result>> = flow {
emit(emptyList()) // initial
emit(repo.search(query)) // suspends, emits result
}
Key operators:
map, filter, transform, flatMapLatest (cancel-previous —
ideal for search-as-you-type), flatMapConcat, flatMapMerge.combine, zip, merge.onStart, onEach, onCompletion, catch (upstream errors only),
retry.flowOn(Dispatchers.IO) changes the upstream
dispatcher; buffer, conflate, debounce, sample.fun results(query: Flow<String>): Flow<UiState> = query
.debounce(300)
.distinctUntilChanged()
.flatMapLatest { q -> repo.search(q) } // cancels stale searches
.map(UiState::Loaded)
.catch { emit(UiState.Error(it)) }
.flowOn(Dispatchers.Default)
Rules:
flowOn to set the producer dispatcher; never call withContext inside a
flow { } builder (it breaks context preservation — the builder enforces this).catch downstream of the operators whose errors you want to handle;
collector-side errors are not caught by catch.These are hot flows for UI state and events.
StateFlow<T> — holds a single current value, conflates, always has a value.
The standard holder for screen UI state. Emit via MutableStateFlow.SharedFlow<T> — broadcasts events to multiple collectors; configurable
replay. Use for one-shot events (navigation, snackbars) with replay = 0.class FeedViewModel(private val repo: FeedRepository) : ViewModel() {
private val _state = MutableStateFlow<FeedUiState>(FeedUiState.Loading)
val state: StateFlow<FeedUiState> = _state.asStateFlow()
init {
viewModelScope.launch {
_state.value = try {
FeedUiState.Loaded(repo.feed())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
FeedUiState.Error(e.message)
}
}
}
}
Convert a cold flow to a lifecycle-aware hot StateFlow with stateIn:
val items: StateFlow<List<Item>> = repo.observeItems()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000), // stop 5s after last collector
initialValue = emptyList()
)
WhileSubscribed(5_000) keeps the upstream alive briefly across configuration
changes while still stopping when nothing observes — the standard choice.
For one-shot events prefer a Channel consumed as a flow, or a SharedFlow with
replay = 0; do not model events as StateFlow (state is re-delivered on
recomposition and replays stale events).
Single value:
suspend fun awaitLocation(): Location = suspendCancellableCoroutine { cont ->
val cb = LocationCallback { loc -> cont.resume(loc) }
locationManager.request(cb)
cont.invokeOnCancellation { locationManager.remove(cb) } // clean up
}
Stream of values:
fun locationUpdates(): Flow<Location> = callbackFlow {
val cb = LocationCallback { loc -> trySend(loc) }
locationManager.request(cb)
awaitClose { locationManager.remove(cb) } // required — cleans up on cancel
}
GlobalScope.launch — no lifecycle, leaks. Use a real scope.runBlocking in production code — blocks the thread; it is for main()
and tests only.CancellationException — breaks structured cancellation;
always rethrow it.Thread.sleep, blocking IO, or heavy CPU on
Dispatchers.Main.withContext inside a flow { } builder — use flowOn instead.collectAsState() in Compose — use
collectAsStateWithLifecycle() so collection pauses in the background.StateFlow — they replay stale events; use a
Channel/SharedFlow(replay = 0).async/await in a coroutineScope.async with a CoroutineExceptionHandler — it
does not fire for async; catch at await.awaitClose in callbackFlow — leaks the callback.GlobalScope; work runs in viewModelScope/lifecycleScope/owned scoperunBlocking outside main/testswithContext pushes the switch down)ensureActive/yield)CancellationException is rethrown, never swallowedsupervisorScope/SupervisorJob where neededflowOn sets upstream dispatcher; no withContext inside flow {}StateFlow (backed by MutableStateFlow)stateIn uses WhileSubscribed(5_000) for screen stateStateFlowcallbackFlow/suspendCancellableCoroutine clean up on cancellationWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub eric-sabe/engsys --plugin engsys-kotlin3 skills in this plugin
/android-testingWrite and review Android/Kotlin tests across the pyramid: JUnit (4/5) unit tests, MockK, Turbine for Flow/StateFlow assertions, coroutine testing with runTest and test dispatchers, Robolectric JVM tests, Espresso instrumented UI tests, and Compose UI testing with createComposeRule and semantics matchers. Use when writing or fixing unit tests, testing coroutines/Flows, mocking dependencies, choosing JVM vs instrumented tests, or testing Compose UI and ViewModels on Android./jetpack-composeBuild Android UIs with Jetpack Compose: composition, state hoisting, remember/rememberSaveable/derivedStateOf, recomposition correctness and performance, side-effect APIs (LaunchedEffect/DisposableEffect/rememberCoroutineScope/produceState/snapshotFlow), Material 3 theming, and Compose navigation. Use when writing or reviewing @Composable functions, fixing recomposition or state bugs, hoisting state, choosing a side-effect API, applying Material 3, or improving Compose performance and stability.