kotlin-coroutines
БесплатноБез исполняемых скриптовНе проверенCoroutines/Flow in Amethyst: picking IO vs Default, scopes and cancellation (CancellationException, withTimeout), StateFlow/SharedFlow/Channel and stateIn…
Об этом скилле
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.
Установить kotlin-coroutines в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл kotlin-coroutines?
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.
Как установить скилл kotlin-coroutines?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл kotlin-coroutines запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic