KO

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.zip

Installs 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.
630 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

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

You give it
Relay lists, filters, Android callbacks, event streams
You get back
Flows of events, managed relay connections, handled exceptions, tested async code

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. Account takes 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.
  • New non-owner classes (helpers, repositories, parsers) expose suspend APIs and do not launch from init. Let the owner pick the scope.
  • No runBlocking outside tests, previews and the CLI entry point. No GlobalScope.

Cancellation and timeouts

  • A broad catch (e: Exception) / runCatching around a suspend call must rethrow CancellationException.
  • TimeoutCancellationException IS a CancellationException. 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 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

  • MutableStateFlow.update { } instead of _s.value = _s.value.copy(...). Keep the block pure and cheap (it can retry); build expensive values before it.
  • stateIn/shareIn belong on a val, never inside a function (each call starts a new sharing coroutine).
  • WhileSubscribed stops upstream with no collectors, so .value goes stale or stays at the initial value. If code reads .value synchronously, use Eagerly.
  • stateFlow.map { } is a plain Flow; terminate with stateIn if consumers need .value.
  • One-shot events for a single consumer (navigation, a toast): a 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.
  • Don't invent fake domain sentinels as the initial value; use null or a sealed loading state.

Tests

  • runTest from kotlinx-coroutines-test, not runBlocking. Turbine is not a dependency; collect into a list in backgroundScope.launch { flow.collect { } } and drive time with advanceUntilIdle(), runCurrent(), advanceTimeBy().
  • Inject the dispatcher/scope under test (StandardTestDispatcher(testScheduler) or UnconfinedTestDispatcher) 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.

SkillInstallsUpdatedSafetyDifficulty
kotlin-coroutines (this skill)310moNo flagsAdvanced
survey-sdk-audit34moReviewIntermediate
android-kotlin77moNo flagsIntermediate
android-jetpack-compose-expert47moNo flagsAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by vitorpamplona

View all by vitorpamplona →

kotlin-multiplatform

vitorpamplona

Platform abstraction decision-making for Amethyst KMP project. Guides when to abstract vs keep platform-specific, source set placement (commonMain, jvmAndroid, platform-specific), expect/actual patterns. Covers primary targets (Android, JVM/Desktop, iOS) with web/wasm future considerations. Integrates with gradle-expert for dependency issues. Triggers on: abstraction decisions ("should I share this?"), source set placement questions, expect/actual creation, build.gradle.kts work, incorrect placement detection, KMP dependency suggestions.

32156

compose-expert

vitorpamplona

Advanced Compose Multiplatform UI patterns for shared composables. Use when working with visual UI components, state management patterns (remember, derivedStateOf, produceState), recomposition optimization (@Stable/@Immutable visual usage), Material3 theming, custom ImageVector icons, or determining whether to share UI in commonMain vs keep platform-specific. Delegates navigation to android-expert/desktop-expert. Complements kotlin-expert (handles Kotlin language aspects of state/annotations).

632

kotlin-expert

vitorpamplona

Advanced Kotlin patterns for AmethystMultiplatform. Flow state management (StateFlow/SharedFlow), sealed hierarchies (classes vs interfaces), immutability (@Immutable, data classes), DSL builders (type-safe fluent APIs), inline functions (reified generics, performance). Use when working with: (1) State management patterns (StateFlow/SharedFlow/MutableStateFlow), (2) Sealed classes or sealed interfaces, (3) @Immutable annotations for Compose, (4) DSL builders with lambda receivers, (5) inline/reified functions, (6) Kotlin performance optimization. Complements kotlin-coroutines agent (async patterns) - this skill focuses on Amethyst-specific Kotlin idioms.

526

nostr-expert

vitorpamplona

Nostr protocol implementation patterns in Quartz (AmethystMultiplatform's KMP Nostr library). Use when working with: (1) Nostr events (creating, parsing, signing), (2) Event kinds and tags, (3) NIP implementations (57 NIPs in quartz/), (4) Event builders and TagArrayBuilder DSL, (5) Nostr cryptography (secp256k1, NIP-44 encryption), (6) Relay communication patterns, (7) Bech32 encoding (npub, nsec, note, nevent). Complements nostr-protocol agent (NIP specs) - this skill provides Quartz codebase patterns and implementation details.

323

gradle-expert

vitorpamplona

Build optimization, dependency resolution, and multi-module KMP troubleshooting for AmethystMultiplatform. Use when working with: (1) Gradle build files (build.gradle.kts, settings.gradle), (2) Version catalog (libs.versions.toml), (3) Build errors and dependency conflicts, (4) Module dependencies and source sets, (5) Desktop packaging (DMG/MSI/DEB), (6) Build performance optimization, (7) Proguard/R8 configuration, (8) Common KMP + Android Gradle issues (Compose conflicts, secp256k1 JNI variants, source set problems).

19

Search skills

Search the agent skills registry