Kotlin coroutines

From vitorpamplona/amethyst · View interactive version

Kotlin coroutines is an AI agent skill from the GitHub repository vitorpamplona/amethyst. Coroutines/Flow in Amethyst: picking IO vs Default, scopes and cancellation (CancellationException, withTimeout), StateFlow/SharedFlow/Channel and stateIn choices, runTest. Use when writing or reviewing async Kotlin code.

How to use this skill

Skill file

Kotlin coroutines in Amethyst

Repo-specific rules only. Textbook coroutines/Flow knowledge is assumed.

Dispatchers

Dispatchers.IO is the default; Default only for provably lock-free CPU work.

The full rule, with the reasons and examples (ParallelEventVerifier,

PoWMiner.MiningDispatcher, BagSweep, NostrSignerExternal), is

commons/ARCHITECTURE.md › "Choosing a dispatcher". Read it before writing

flowOn/withContext. In commonMain, Dispatchers.IO needs

import kotlinx.coroutines.IO.

Relay work: reuse, don't hand-roll

Never write your own callbackFlow { openReqSubscription(...); awaitClose { ... } }

REQ loop. One-shot and paged fetches, publish-and-confirm, COUNT and negentropy sync

already exist as INostrClient extensions in

quartz/src/commonMain/kotlin/com/vitorpamplona/quartz/nip01Core/relay/client/accessories/

(catalog: its README.md; flow helpers in ../reqs/). Their timeouts are idle

windows (idleTimeoutMs), not deadlines. For loads tied to a composable's lifetime,

see the relay-client skill.

callbackFlow is still the right bridge for platform callbacks; copy

amethyst/.../service/connectivity/ConnectivityFlow.kt (initial emit, awaitClose

unregister, distinctUntilChanged().debounce(200).flowOn(Dispatchers.IO)).

Scopes

scope: CoroutineScope; Android services build

CoroutineScope(Dispatchers.IO + SupervisorJob() + exceptionHandler) and

cancel() it in onDestroy (PushNotificationReceiverService). Hundreds of

such fields are legitimate; don't flag them on sight.

and do not launch from init. Let the owner pick the scope.

GlobalScope.

Cancellation and timeouts

CancellationException.

rethrow turns one slow RPC into a dead loop: rethrowing it ended the cordn sync

loop for the whole session. Either catch the timeout narrowly, right at the

withTimeout, or rethrow only when the coroutine itself is cancelled

(if (!isActive) throw e). See cordn-kmp's cordn/client/CordnSyncLoop.kt for both.

State and events

block pure and cheap (it can retry); build expensive values before it.

new sharing coroutine).

stays at the initial value. If code reads .value synchronously, use Eagerly.

need .value.

Channel(Channel.BUFFERED).receiveAsFlow(), not a no-replay MutableSharedFlow

that drops emissions with no collector. A Channel delivers each item to ONE

collector; if every observer must see it, model it as state.

loading state.

Tests

dependency; collect into a list in backgroundScope.launch { flow.collect { } }

and drive time with advanceUntilIdle(), runCurrent(), advanceTimeBy().

or UnconfinedTestDispatcher) so delays run on virtual time.

loaded CI). Wait on the test scheduler or a condition.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.