0
# kotlinx-coroutines-core
1
2
kotlinx-coroutines-core is a comprehensive Kotlin multiplatform library that provides structured concurrency support for asynchronous programming. It offers coroutine builders, reactive flows, communication channels, synchronization primitives, and platform-specific integrations while maintaining structured concurrency principles and automatic cancellation support.
3
4
## Package Information
5
6
- **Package Name**: org.jetbrains.kotlinx:kotlinx-coroutines-core-iosx64
7
- **Package Type**: maven
8
- **Language**: Kotlin (multiplatform)
9
- **Installation**: Add to your `build.gradle.kts` dependencies:
10
```kotlin
11
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-iosx64:1.10.2")
12
```
13
14
## Core Imports
15
16
```kotlin
17
import kotlinx.coroutines.*
18
import kotlinx.coroutines.flow.*
19
import kotlinx.coroutines.channels.*
20
import kotlinx.coroutines.sync.*
21
```
22
23
For specific imports:
24
```kotlin
25
import kotlinx.coroutines.launch
26
import kotlinx.coroutines.async
27
import kotlinx.coroutines.flow.Flow
28
import kotlinx.coroutines.flow.flowOf
29
import kotlinx.coroutines.channels.Channel
30
import kotlinx.coroutines.sync.Mutex
31
```
32
33
## Basic Usage
34
35
```kotlin
36
import kotlinx.coroutines.*
37
import kotlinx.coroutines.flow.*
38
39
class CoroutineExample {
40
suspend fun basicUsage() {
41
// Create a coroutine scope
42
val scope = CoroutineScope(Dispatchers.Default)
43
44
// Launch fire-and-forget coroutines
45
val job = scope.launch {
46
delay(100)
47
println("Hello from coroutine!")
48
}
49
50
// Launch concurrent computation
51
val deferred = scope.async {
52
delay(50)
53
"Result from async"
54
}
55
56
// Work with flows
57
val flow = flowOf(1, 2, 3, 4, 5)
58
.map { it * 2 }
59
.filter { it > 5 }
60
61
flow.collect { value ->
62
println("Flow value: $value")
63
}
64
65
// Wait for completion
66
val result = deferred.await()
67
job.join()
68
}
69
}
70
```
71
72
## Architecture
73
74
kotlinx-coroutines-core is built around several key architectural components:
75
76
- **Structured Concurrency**: Job hierarchy ensures automatic cleanup and cancellation propagation
77
- **Coroutine Builders**: `launch`, `async`, `runBlocking` for creating different types of coroutines
78
- **Dispatchers**: Context switching for different execution environments (Main, Default, IO, Unconfined)
79
- **Flow API**: Cold reactive streams with comprehensive operators and hot flows (SharedFlow/StateFlow)
80
- **Channels**: Communication primitives between coroutines with various buffer strategies
81
- **Synchronization**: Mutex and Semaphore for coordination without blocking threads
82
- **Platform Integration**: Native support for platform-specific threading models and async APIs
83
84
## Capabilities
85
86
### Coroutine Management
87
88
Core lifecycle management for coroutines including Job interface, scoping, and structured concurrency support.
89
90
```kotlin { .api }
91
interface Job : CoroutineContext.Element {
92
val isActive: Boolean
93
val isCompleted: Boolean
94
val isCancelled: Boolean
95
val children: Sequence<Job>
96
fun start(): Boolean
97
fun cancel(): Unit
98
suspend fun join(): Unit
99
}
100
101
interface CoroutineScope {
102
val coroutineContext: CoroutineContext
103
}
104
105
fun CoroutineScope(context: CoroutineContext): CoroutineScope
106
fun MainScope(): CoroutineScope
107
```
108
109
[Coroutine Management](./coroutine-management.md)
110
111
### Coroutine Builders
112
113
Functions for creating and launching coroutines with different execution patterns and result handling.
114
115
```kotlin { .api }
116
fun CoroutineScope.launch(
117
context: CoroutineContext = EmptyCoroutineContext,
118
start: CoroutineStart = CoroutineStart.DEFAULT,
119
block: suspend CoroutineScope.() -> Unit
120
): Job
121
122
fun <T> CoroutineScope.async(
123
context: CoroutineContext = EmptyCoroutineContext,
124
start: CoroutineStart = CoroutineStart.DEFAULT,
125
block: suspend CoroutineScope.() -> T
126
): Deferred<T>
127
128
suspend fun <T> withContext(
129
context: CoroutineContext,
130
block: suspend CoroutineScope.() -> T
131
): T
132
```
133
134
[Coroutine Builders](./coroutine-builders.md)
135
136
### Flow API
137
138
Cold reactive streams with comprehensive transformation operators, hot flows for state and event broadcasting.
139
140
```kotlin { .api }
141
interface Flow<out T> {
142
suspend fun collect(collector: FlowCollector<T>)
143
}
144
145
interface FlowCollector<in T> {
146
suspend fun emit(value: T)
147
}
148
149
fun <T> flow(block: suspend FlowScope<T>.() -> Unit): Flow<T>
150
fun <T> flowOf(vararg elements: T): Flow<T>
151
152
interface SharedFlow<out T> : Flow<T> {
153
val replayCache: List<T>
154
}
155
156
interface StateFlow<out T> : SharedFlow<T> {
157
val value: T
158
}
159
```
160
161
[Flow API](./flow-api.md)
162
163
### Channels
164
165
Communication primitives between coroutines with various buffering strategies and channel types.
166
167
```kotlin { .api }
168
interface SendChannel<in E> {
169
val isClosedForSend: Boolean
170
suspend fun send(element: E)
171
fun trySend(element: E): ChannelResult<Unit>
172
fun close(cause: Throwable? = null): Boolean
173
}
174
175
interface ReceiveChannel<out E> {
176
val isClosedForReceive: Boolean
177
val isEmpty: Boolean
178
suspend fun receive(): E
179
fun tryReceive(): ChannelResult<E>
180
}
181
182
interface Channel<E> : SendChannel<E>, ReceiveChannel<E>
183
184
fun <E> Channel(
185
capacity: Int = RENDEZVOUS,
186
onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,
187
onUndeliveredElement: ((E) -> Unit)? = null
188
): Channel<E>
189
```
190
191
[Channels](./channels.md)
192
193
### Synchronization
194
195
Non-blocking synchronization primitives including mutex and semaphore for coroutine coordination.
196
197
```kotlin { .api }
198
interface Mutex {
199
val isLocked: Boolean
200
suspend fun lock(owner: Any? = null)
201
fun unlock(owner: Any? = null)
202
fun tryLock(owner: Any? = null): Boolean
203
}
204
205
suspend fun <T> Mutex.withLock(
206
owner: Any? = null,
207
action: suspend () -> T
208
): T
209
210
interface Semaphore {
211
val availablePermits: Int
212
suspend fun acquire()
213
fun release()
214
fun tryAcquire(): Boolean
215
}
216
```
217
218
[Synchronization](./synchronization.md)
219
220
### Dispatchers
221
222
Execution context control for coroutines including standard dispatchers and custom dispatcher creation.
223
224
```kotlin { .api }
225
abstract class CoroutineDispatcher : ContinuationInterceptor {
226
abstract fun dispatch(context: CoroutineContext, block: Runnable)
227
open fun isDispatchNeeded(context: CoroutineContext): Boolean
228
fun limitedParallelism(parallelism: Int): CoroutineDispatcher
229
}
230
231
object Dispatchers {
232
val Default: CoroutineDispatcher
233
val Main: MainCoroutineDispatcher
234
val Unconfined: CoroutineDispatcher
235
val IO: CoroutineDispatcher
236
}
237
```
238
239
[Dispatchers](./dispatchers.md)
240
241
### Select Expression
242
243
Multi-way suspending choice allowing selection among multiple suspend operations.
244
245
```kotlin { .api }
246
suspend fun <R> select(builder: SelectBuilder<R>.() -> Unit): R
247
248
interface SelectBuilder<in R> {
249
fun <T> SelectClause1<T>.invoke(block: suspend (T) -> R)
250
fun SelectClause0.invoke(block: suspend () -> R)
251
fun onTimeout(timeMillis: Long, block: suspend () -> R)
252
}
253
```
254
255
[Select Expression](./select-expression.md)
256
257
### Error Handling & Cancellation
258
259
Cancellation propagation, exception handling, and timeout management for robust coroutine applications.
260
261
```kotlin { .api }
262
open class CancellationException : IllegalStateException
263
264
suspend fun <T> withTimeout(timeoutMillis: Long, block: suspend CoroutineScope.() -> T): T
265
suspend fun <T> withTimeoutOrNull(timeoutMillis: Long, block: suspend CoroutineScope.() -> T): T?
266
267
class TimeoutCancellationException : CancellationException
268
269
interface CoroutineExceptionHandler : CoroutineContext.Element {
270
fun handleException(context: CoroutineContext, exception: Throwable)
271
}
272
```
273
274
[Error Handling & Cancellation](./error-handling.md)
275
276
## Types
277
278
### Core Context Types
279
280
```kotlin { .api }
281
enum class CoroutineStart {
282
DEFAULT,
283
LAZY,
284
ATOMIC,
285
UNDISPATCHED
286
}
287
288
interface Deferred<out T> : Job {
289
suspend fun await(): T
290
fun getCompleted(): T
291
fun getCompletionExceptionOrNull(): Throwable?
292
}
293
294
interface CompletableJob : Job {
295
fun complete(): Boolean
296
fun completeExceptionally(exception: Throwable): Boolean
297
}
298
299
interface CompletableDeferred<T> : Deferred<T>, CompletableJob
300
301
data class CoroutineName(val name: String) : CoroutineContext.Element
302
```
303
304
### Buffer & Flow Types
305
306
```kotlin { .api }
307
enum class BufferOverflow {
308
SUSPEND,
309
DROP_OLDEST,
310
DROP_LATEST
311
}
312
313
interface SharingStarted {
314
companion object {
315
val Eagerly: SharingStarted
316
val Lazily: SharingStarted
317
fun WhileSubscribed(
318
stopTimeoutMillis: Long = 0,
319
replayExpirationMillis: Long = Long.MAX_VALUE
320
): SharingStarted
321
}
322
}
323
```