kotlin-coroutines
Provides advanced patterns for Kotlin coroutines in Amethyst, including Flow operators, structured concurrency, and async testing.
Install
mkdir -p .claude/skills/kotlin-coroutines && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/3062" && unzip -o skill.zip -d .claude/skills/kotlin-coroutines && rm skill.zipInstalls to .claude/skills/kotlin-coroutines
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Advanced Kotlin coroutines patterns for AmethystMultiplatform. Use when working with: (1) Structured concurrency (supervisorScope, coroutineScope), (2) Advanced Flow operators (flatMapLatest, combine, merge, shareIn, stateIn), (3) Channels and callbackFlow, (4) Dispatcher management and context switching, (5) Exception handling (CoroutineExceptionHandler, SupervisorJob), (6) Testing async code (runTest, Turbine), (7) Nostr relay connection pools and subscriptions, (8) Backpressure handling in event streams. Delegates to kotlin-expert for basic StateFlow/SharedFlow patterns. Complements nostr-expert for relay communication.Key capabilities
- →Manage multi-relay subscriptions using supervisorScope
- →Implement callbackFlow for Android callbacks
- →Handle backpressure in high-frequency event streams
- →Manage exceptions with CoroutineExceptionHandler
- →Test asynchronous code with runTest and Turbine
How it works
This skill provides advanced Kotlin coroutines patterns for managing complex asynchronous operations, including structured concurrency, Flow operators, channels, and exception handling, specifically for the AmethystMultiplatform project.
Inputs & outputs
When to use kotlin-coroutines
- →Implementing multi-relay subscriptions
- →Handling backpressure in event streams
- →Testing asynchronous code with Turbine
- →Managing complex callbackFlows
About this skill
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
- Stored scopes are fine for lifecycle owners.
Accounttakesscope: CoroutineScope; Android services buildCoroutineScope(Dispatchers.IO + SupervisorJob() + exceptionHandler)andcancel()it inonDestroy(PushNotificationReceiverService). Hundreds of such fields are legitimate; don't flag them on sight. - New non-owner classes (helpers, repositories, parsers) expose
suspendAPIs and do notlaunchfrominit. Let the owner pick the scope. - No
runBlockingoutside tests, previews and the CLI entry point. NoGlobalScope.
Cancellation and timeouts
- A broad
catch (e: Exception)/runCatchingaround a suspend call must rethrowCancellationException. TimeoutCancellationExceptionIS aCancellationException. A blanket 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 thewithTimeout, or rethrow only when the coroutine itself is cancelled (if (!isActive) throw e). See cordn-kmp'scordn/client/CordnSyncLoop.ktfor both.
State and events
MutableStateFlow.update { }instead of_s.value = _s.value.copy(...). Keep the block pure and cheap (it can retry); build expensive values before it.stateIn/shareInbelong on aval, never inside a function (each call starts a new sharing coroutine).WhileSubscribedstops upstream with no collectors, so.valuegoes stale or stays at the initial value. If code reads.valuesynchronously, useEagerly.stateFlow.map { }is a plainFlow; terminate withstateInif consumers need.value.- One-shot events for a single consumer (navigation, a toast): a
Channel(Channel.BUFFERED).receiveAsFlow(), not a no-replayMutableSharedFlowthat drops emissions with no collector. AChanneldelivers each item to ONE collector; if every observer must see it, model it as state. - Don't invent fake domain sentinels as the initial value; use
nullor a sealed loading state.
Tests
runTestfromkotlinx-coroutines-test, notrunBlocking. Turbine is not a dependency; collect into a list inbackgroundScope.launch { flow.collect { } }and drive time withadvanceUntilIdle(),runCurrent(),advanceTimeBy().- Inject the dispatcher/scope under test (
StandardTestDispatcher(testScheduler)orUnconfinedTestDispatcher) so delays run on virtual time. - Never wait on wall-clock time (
delay(350)racing a 200 ms timeout flaked on loaded CI). Wait on the test scheduler or a condition.
How it compares
This skill focuses on advanced coroutine patterns like supervisorScope and callbackFlow for specific application architectures, unlike basic StateFlow/SharedFlow usage.
Compared to similar skills
kotlin-coroutines side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| kotlin-coroutines (this skill) | 3 | 10mo | No flags | Advanced |
| survey-sdk-audit | 3 | 4mo | Review | Intermediate |
| android-kotlin | 7 | 7mo | No flags | Intermediate |
| android-jetpack-compose-expert | 4 | 7mo | No flags | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by vitorpamplona
View all by vitorpamplona →You might also like
survey-sdk-audit
PostHog
Audit PostHog survey SDK features and version requirements
android-kotlin
alinaqi
Android Kotlin development with Coroutines, Jetpack Compose, Hilt, and MockK testing
android-jetpack-compose-expert
sickn33
Expert guidance for building modern Android UIs with Jetpack Compose, covering state management, navigation, performance, and Material Design 3.
testing-android-code
bitwarden
This skill should be used when writing or reviewing tests for Android code in Bitwarden. Triggered by "BaseViewModelTest", "BitwardenComposeTest", "BaseServiceTest", "stateEventFlow", "bufferedMutableSharedFlow", "FakeDispatcherManager", "expectNoEvents", "assertCoroutineThrows", "createMockCipher", "createMockSend", "asSuccess", "Why is my Bitwarden test failing?", or testing questions about ViewModels, repositories, Compose screens, or data sources in Bitwarden.
create-unit-test
AnySoftKeyboard
Create and run unit tests following the project's architecture and guidelines (Robolectric, naming, location).
extensions-api-migration
JetBrains
Migrates IdeaVim extensions from the old VimExtensionFacade API to the new @VimPlugin annotation-based API. Use when converting existing extensions to use the new API patterns.