Coroutines support libraries for Kotlin providing structured concurrency primitives, Flow API for reactive streams, channels for communication, and synchronization utilities across all Kotlin platforms
npx @tessl/cli install tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core@1.10.00
# kotlinx-coroutines-core
1
2
kotlinx-coroutines-core is the foundational library for structured concurrency in Kotlin, providing comprehensive asynchronous programming capabilities. It offers coroutine builders, Flow API for reactive streams, channels for communication between coroutines, and synchronization primitives for concurrent programming across all Kotlin platforms.
3
4
## Package Information
5
6
- **Package Name**: kotlinx-coroutines-core
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Platform**: Kotlin Multiplatform (JVM, Android, JS, Native)
10
- **Installation**: Add `implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")` to your Gradle dependencies
11
12
## Core Imports
13
14
```kotlin
15
import kotlinx.coroutines.*
16
import kotlinx.coroutines.flow.*
17
import kotlinx.coroutines.channels.*
18
import kotlinx.coroutines.sync.*
19
```
20
21
For specific functionality:
22
23
```kotlin
24
// Core coroutine builders and scope
25
import kotlinx.coroutines.launch
26
import kotlinx.coroutines.async
27
import kotlinx.coroutines.CoroutineScope
28
import kotlinx.coroutines.MainScope
29
30
// Flow API
31
import kotlinx.coroutines.flow.Flow
32
import kotlinx.coroutines.flow.StateFlow
33
import kotlinx.coroutines.flow.MutableStateFlow
34
35
// Channels
36
import kotlinx.coroutines.channels.Channel
37
import kotlinx.coroutines.channels.produce
38
39
// Dispatchers
40
import kotlinx.coroutines.Dispatchers
41
```
42
43
## Basic Usage
44
45
```kotlin
46
import kotlinx.coroutines.*
47
import kotlinx.coroutines.flow.*
48
49
// Create a coroutine scope
50
val scope = MainScope()
51
52
// Launch a fire-and-forget coroutine
53
val job = scope.launch {
54
delay(1000)
55
println("Coroutine completed!")
56
}
57
58
// Launch a coroutine that returns a result
59
val deferred = scope.async {
60
delay(500)
61
"Hello from async!"
62
}
63
64
// Create and collect a Flow
65
val numberFlow = flow {
66
for (i in 1..5) {
67
emit(i)
68
delay(100)
69
}
70
}
71
72
scope.launch {
73
numberFlow.collect { value ->
74
println("Received: $value")
75
}
76
}
77
78
// Wait for results
79
scope.launch {
80
val result = deferred.await()
81
println(result)
82
}
83
```
84
85
## Architecture
86
87
kotlinx-coroutines-core is built around several key architectural components:
88
89
- **Structured Concurrency**: Jobs form parent-child hierarchies where cancellation propagates automatically
90
- **Coroutine Contexts**: Composable context elements (dispatchers, jobs, exception handlers) that define execution environment
91
- **Suspend Functions**: Functions that can pause execution without blocking threads
92
- **Dispatchers**: Thread pools and execution contexts for running coroutines
93
- **Flow API**: Cold streams for reactive programming with rich operator support
94
- **Channel API**: Hot communication primitives for producer-consumer patterns
95
- **Cancellation Model**: Cooperative cancellation system with structured cleanup
96
97
## Capabilities
98
99
### Coroutine Builders and Scope Management
100
101
Core building blocks for creating and managing coroutines with structured concurrency guarantees.
102
103
```kotlin { .api }
104
interface CoroutineScope {
105
val coroutineContext: CoroutineContext
106
}
107
108
fun CoroutineScope.launch(
109
context: CoroutineContext = EmptyCoroutineContext,
110
start: CoroutineStart = CoroutineStart.DEFAULT,
111
block: suspend CoroutineScope.() -> Unit
112
): Job
113
114
fun <T> CoroutineScope.async(
115
context: CoroutineContext = EmptyCoroutineContext,
116
start: CoroutineStart = CoroutineStart.DEFAULT,
117
block: suspend CoroutineScope.() -> T
118
): Deferred<T>
119
120
fun CoroutineScope(context: CoroutineContext): CoroutineScope
121
fun MainScope(): CoroutineScope
122
```
123
124
[Coroutine Builders and Scopes](./coroutine-builders.md)
125
126
### Job and Deferred Management
127
128
Lifecycle management for coroutines including cancellation, completion tracking, and result handling.
129
130
```kotlin { .api }
131
interface Job : CoroutineContext.Element {
132
val isActive: Boolean
133
val isCompleted: Boolean
134
val isCancelled: Boolean
135
val children: Sequence<Job>
136
137
fun start(): Boolean
138
fun cancel(cause: CancellationException? = null)
139
suspend fun join()
140
}
141
142
interface Deferred<out T> : Job {
143
suspend fun await(): T
144
fun getCompleted(): T
145
val onAwait: SelectClause1<T>
146
}
147
148
interface CompletableJob : Job {
149
fun complete(): Boolean
150
fun completeExceptionally(exception: Throwable): Boolean
151
}
152
```
153
154
[Jobs and Deferreds](./jobs-deferreds.md)
155
156
### Coroutine Dispatchers
157
158
Thread management and execution contexts for controlling where coroutines run.
159
160
```kotlin { .api }
161
abstract class CoroutineDispatcher : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
162
abstract fun dispatch(context: CoroutineContext, block: Runnable)
163
open fun isDispatchNeeded(context: CoroutineContext): Boolean
164
fun limitedParallelism(parallelism: Int): CoroutineDispatcher
165
}
166
167
object Dispatchers {
168
val Default: CoroutineDispatcher
169
val Main: MainCoroutineDispatcher
170
val Unconfined: CoroutineDispatcher
171
}
172
173
abstract class MainCoroutineDispatcher : CoroutineDispatcher() {
174
abstract val immediate: MainCoroutineDispatcher
175
}
176
```
177
178
[Dispatchers](./dispatchers.md)
179
180
### Flow API - Reactive Streams
181
182
Asynchronous data streams with rich operator support for reactive programming patterns.
183
184
```kotlin { .api }
185
interface Flow<out T> {
186
suspend fun collect(collector: FlowCollector<T>)
187
}
188
189
interface FlowCollector<in T> {
190
suspend fun emit(value: T)
191
}
192
193
interface StateFlow<out T> : SharedFlow<T> {
194
val value: T
195
}
196
197
interface MutableStateFlow<T> : StateFlow<T>, MutableSharedFlow<T> {
198
override var value: T
199
fun compareAndSet(expect: T, update: T): Boolean
200
}
201
202
fun <T> MutableStateFlow<T>.update(function: (T) -> T)
203
fun <T> MutableStateFlow<T>.updateAndGet(function: (T) -> T): T
204
fun <T> MutableStateFlow<T>.getAndUpdate(function: (T) -> T): T
205
206
interface SharedFlow<out T> : Flow<T> {
207
val replayCache: List<T>
208
val subscriptionCount: StateFlow<Int>
209
}
210
211
interface MutableSharedFlow<T> : SharedFlow<T>, FlowCollector<T> {
212
fun tryEmit(value: T): Boolean
213
fun resetReplayCache()
214
}
215
```
216
217
[Flow API](./flow-api.md)
218
219
### Channel API - Communication Primitives
220
221
Producer-consumer communication channels for passing data between coroutines.
222
223
```kotlin { .api }
224
interface Channel<E> : SendChannel<E>, ReceiveChannel<E>
225
226
interface SendChannel<in E> {
227
val isClosedForSend: Boolean
228
suspend fun send(element: E)
229
fun trySend(element: E): ChannelResult<Unit>
230
fun close(cause: Throwable? = null): Boolean
231
}
232
233
interface ReceiveChannel<out E> {
234
val isClosedForReceive: Boolean
235
suspend fun receive(): E
236
fun tryReceive(): ChannelResult<E>
237
fun cancel(cause: CancellationException? = null)
238
}
239
240
fun <E> Channel(
241
capacity: Int = Channel.RENDEZVOUS,
242
onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,
243
onUndeliveredElement: ((E) -> Unit)? = null
244
): Channel<E>
245
```
246
247
[Channels](./channels.md)
248
249
### Synchronization Primitives
250
251
Thread-safe synchronization utilities for coordinating access to shared resources.
252
253
```kotlin { .api }
254
interface Mutex {
255
val isLocked: Boolean
256
suspend fun lock(owner: Any? = null)
257
fun tryLock(owner: Any? = null): Boolean
258
fun unlock(owner: Any? = null)
259
suspend fun <T> withLock(owner: Any? = null, action: suspend () -> T): T
260
}
261
262
interface Semaphore {
263
val availablePermits: Int
264
suspend fun acquire()
265
fun tryAcquire(): Boolean
266
fun release()
267
suspend fun <T> withPermit(action: suspend () -> T): T
268
}
269
270
fun Mutex(locked: Boolean = false): Mutex
271
fun Semaphore(permits: Int, acquiredPermits: Int = 0): Semaphore
272
```
273
274
[Synchronization](./synchronization.md)
275
276
### Structured Concurrency Functions
277
278
Scoping functions and cancellation management for coordinated lifecycle management.
279
280
```kotlin { .api }
281
suspend fun <T> coroutineScope(block: suspend CoroutineScope.() -> T): T
282
suspend fun <T> supervisorScope(block: suspend CoroutineScope.() -> T): T
283
suspend fun <T> withContext(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T
284
suspend fun <T> withTimeout(timeoutMillis: Long, block: suspend CoroutineScope.() -> T): T
285
suspend fun <T> withTimeoutOrNull(timeoutMillis: Long, block: suspend CoroutineScope.() -> T): T?
286
287
suspend fun delay(timeMillis: Long)
288
suspend fun delay(duration: Duration)
289
suspend fun yield()
290
suspend fun awaitCancellation(): Nothing
291
suspend fun currentCoroutineContext(): CoroutineContext
292
fun CoroutineContext.ensureActive()
293
```
294
295
[Structured Concurrency](./structured-concurrency.md)
296
297
### Select Expressions
298
299
Advanced multiplexing primitive for waiting on multiple suspending operations simultaneously.
300
301
```kotlin { .api }
302
suspend fun <R> select(builder: SelectBuilder<R>.() -> Unit): R
303
suspend fun <R> selectUnbiased(builder: SelectBuilder<R>.() -> Unit): R
304
305
interface SelectBuilder<in R> {
306
fun onTimeout(timeMillis: Long, block: suspend () -> R)
307
}
308
309
// Select clauses available on various types
310
val Job.onJoin: SelectClause0
311
val <T> Deferred<T>.onAwait: SelectClause1<T>
312
val <E> SendChannel<E>.onSend: SelectClause2<E, SendChannel<E>>
313
val <E> ReceiveChannel<E>.onReceive: SelectClause1<E>
314
val <E> ReceiveChannel<E>.onReceiveCatching: SelectClause1<ChannelResult<E>>
315
```
316
317
### Exception Handling and Cancellation
318
319
Comprehensive error handling and cancellation mechanisms for robust coroutine applications.
320
321
```kotlin { .api }
322
interface CoroutineExceptionHandler : CoroutineContext.Element {
323
fun handleException(context: CoroutineContext, exception: Throwable)
324
}
325
326
open class CancellationException(message: String? = null, cause: Throwable? = null) : IllegalStateException(message, cause)
327
class TimeoutCancellationException(message: String?, coroutine: Job) : CancellationException(message)
328
329
object NonCancellable : AbstractCoroutineContextElement(Job), Job
330
fun SupervisorJob(parent: Job? = null): CompletableJob
331
```
332
333
[Exception Handling](./exception-handling.md)
334
335
## Types
336
337
### Core Context Types
338
339
```kotlin { .api }
340
enum class CoroutineStart {
341
DEFAULT, LAZY, ATOMIC, UNDISPATCHED
342
}
343
344
data class CoroutineName(val name: String) : AbstractCoroutineContextElement(CoroutineName)
345
346
enum class BufferOverflow {
347
SUSPEND, DROP_OLDEST, DROP_LATEST
348
}
349
350
object GlobalScope : CoroutineScope {
351
override val coroutineContext: CoroutineContext
352
}
353
354
// Select clause interfaces
355
interface SelectClause0
356
interface SelectClause1<out T>
357
interface SelectClause2<in P, out T>
358
359
// Duration support
360
typealias Duration = kotlin.time.Duration
361
```
362
363
### Flow Sharing Configuration
364
365
```kotlin { .api }
366
interface SharingStarted {
367
companion object {
368
val Eagerly: SharingStarted
369
val Lazily: SharingStarted
370
fun WhileSubscribed(
371
stopTimeoutMillis: Long = Long.MAX_VALUE,
372
replayExpirationMillis: Long = Long.MAX_VALUE
373
): SharingStarted
374
}
375
}
376
```
377
378
### Channel Configuration
379
380
```kotlin { .api }
381
object Channel {
382
const val RENDEZVOUS = 0
383
const val CONFLATED = -1
384
const val UNLIMITED = Int.MAX_VALUE
385
const val BUFFERED = -2
386
const val CHANNEL_DEFAULT_CAPACITY = 64
387
}
388
389
value class ChannelResult<out T> {
390
val isSuccess: Boolean
391
val isClosed: Boolean
392
val isFailure: Boolean
393
394
fun getOrNull(): T?
395
fun exceptionOrNull(): Throwable?
396
}
397
```