kotlin-coroutines
Kotlin coroutines on the JVM: suspend functions, structured concurrency (coroutineScope, supervisorScope, application-owned scopes), dispatchers and blocking I/O, cancellation and CancellationExceptio
Files1
View on GitHubSKILL.mdplugins/kotlin-plugin/skills/kotlin-coroutines/SKILL.md
GitHubKotlin Coroutines
Suspend functions
- A function that does I/O or waits is
suspend. It must be main-safe: callers can invoke it from any dispatcher, so it switches context itself when it blocks.
class ReportRepository(private val io: CoroutineDispatcher = Dispatchers.IO) {
suspend fun load(path: Path): Report = withContext(io) {
Files.newBufferedReader(path).use { parse(it) } // blocking JDBC/file/HTTP-client calls live here
}
}
- Inject the dispatcher (constructor parameter with a default) so tests can pass a test dispatcher.
- Do not make a function
suspendif it never suspends. - Non-blocking clients (Ktor client, R2DBC, async drivers) need no
withContext(IO).
Structured concurrency
- Every coroutine has an owner scope that outlives it and cancels it:
- inside a suspend function →
coroutineScope { }(one failure cancels siblings) orsupervisorScope { }(children fail independently); - in a Ktor handler → the call's coroutine;
- for app-lifetime background work → a scope the application creates and cancels on shutdown (
CoroutineScope(SupervisorJob() + Dispatchers.Default)owned by a component withclose()).
- inside a suspend function →
- Never
GlobalScope. NeverrunBlockingexcept inmainor tests — inside a server it blocks a request thread and can deadlock. - Parallel independent calls:
suspend fun dashboard(userId: UserId): Dashboard = coroutineScope {
val orders = async { orderClient.recent(userId) }
val profile = async { profileClient.get(userId) }
Dashboard(orders.await(), profile.await())
}
- Bound fan-out over large lists (
Semaphore,chunked, orflatMapMerge(concurrency = N)) — nevermap { async { } }over thousands of items.
Cancellation
- Cancellation is cooperative: long CPU loops call
ensureActive()/yield(). - Never swallow
CancellationException. A broad catch around suspend calls must rethrow it:
try {
client.send(event)
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
log.warn("send failed", e)
}
runCatching { suspendCall() }swallows cancellation — avoid it around suspend calls, or rethrowCancellationExceptionfrom the failure.- Cleanup in
finally; suspending cleanup needswithContext(NonCancellable) { … }. - Timeouts:
withTimeout(5.seconds) { … }(throwsTimeoutCancellationException) orwithTimeoutOrNull.
Exceptions
- In
coroutineScope/async, exceptions propagate to the caller ofawait/the scope — handle them there. CoroutineExceptionHandleronly on root coroutines of an app-owned scope, for logging; it does not make failures recoverable.launchfor fire-and-forget within a scope; its failures cancel the parent unless under aSupervisorJob.
Flow
Flowis cold: nothing runs until collected. Build withflow { emit(…) },channelFlow { }for concurrent producers,callbackFlow { … awaitClose { unregister() } }for callback APIs.- Change upstream context with
flowOn(io), neverwithContextinsideflow { }aroundemit. - Operators:
map,filter,onEach,catch(upstream errors only),retryWhen,debounce,distinctUntilChanged,flatMapLatest. - Hot state:
StateFlow(current value, conflated) viaMutableStateFlowkept private and exposed asStateFlow; events:SharedFlow. Convert a cold flow withstateIn(scope, SharingStarted.WhileSubscribed(5_000), initial). - Ktor server-sent events / WebSockets: collect flows inside the route's coroutine so they cancel with the connection.
Bridging
- Java
CompletableFuture→future.await()(kotlinx-coroutines-jdk8, built into core on recent versions). - Callback API →
suspendCancellableCoroutine { cont -> … cont.invokeOnCancellation { cancel() } }. - Exposing to Java callers → a non-suspend facade returning
CompletableFutureviascope.future { }.
Ktor specifics
- Route handlers already run in a coroutine — call suspend functions directly; wrap only blocking calls in
withContext(Dispatchers.IO). - Do not launch work that must outlive the request in
call's scope; hand it to an application-owned scope or a queue.