0
# Coroutines
1
2
JavaScript-specific coroutine support with generator-based execution and event loop integration for asynchronous programming. This module provides the runtime support needed for Kotlin coroutines to work efficiently in JavaScript environments.
3
4
## Capabilities
5
6
### Core Coroutine Intrinsics
7
8
Low-level coroutine creation and execution functions.
9
10
```kotlin { .api }
11
/**
12
* Starts coroutine without dispatching, returns COROUTINE_SUSPENDED if suspended
13
*/
14
fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn(completion: Continuation<T>): Any?
15
16
/**
17
* Creates unintercepted coroutine without starting it
18
*/
19
fun <T> (suspend () -> T).createCoroutineUnintercepted(completion: Continuation<T>): Continuation<Unit>
20
21
/**
22
* Intercepts continuation with current continuation interceptor
23
*/
24
fun <T> Continuation<T>.intercepted(): Continuation<T>
25
26
/**
27
* Continuation interface for coroutine execution
28
*/
29
interface Continuation<in T> {
30
val context: CoroutineContext
31
fun resumeWith(result: Result<T>)
32
}
33
```
34
35
**Usage Examples:**
36
37
```kotlin
38
import kotlin.coroutines.*
39
40
// Create and start a coroutine
41
suspend fun fetchData(): String {
42
// Simulate async operation
43
return "Data loaded"
44
}
45
46
fun startCoroutine() {
47
val continuation = object : Continuation<String> {
48
override val context = EmptyCoroutineContext
49
50
override fun resumeWith(result: Result<String>) {
51
result.fold(
52
onSuccess = { data -> console.log("Success: $data") },
53
onFailure = { error -> console.error("Error: $error") }
54
)
55
}
56
}
57
58
// Start the coroutine
59
::fetchData.startCoroutineUninterceptedOrReturn(continuation)
60
}
61
```
62
63
### Coroutine Cancellation
64
65
Exception-based cancellation mechanism for coroutines.
66
67
```kotlin { .api }
68
/**
69
* Exception thrown when coroutine is cancelled
70
*/
71
class CancellationException : IllegalStateException {
72
constructor()
73
constructor(message: String?)
74
constructor(message: String?, cause: Throwable?)
75
constructor(cause: Throwable?)
76
}
77
```
78
79
**Usage Examples:**
80
81
```kotlin
82
import kotlin.coroutines.cancellation.CancellationException
83
84
suspend fun cancellableOperation(): String {
85
// Check for cancellation
86
if (/* some cancellation condition */) {
87
throw CancellationException("Operation was cancelled")
88
}
89
90
return "Operation completed"
91
}
92
93
// Handle cancellation
94
try {
95
val result = cancellableOperation()
96
console.log("Result: $result")
97
} catch (e: CancellationException) {
98
console.log("Operation was cancelled: ${e.message}")
99
}
100
```
101
102
### JavaScript-Specific Implementation
103
104
Internal implementation details optimized for JavaScript runtime.
105
106
```kotlin { .api }
107
/**
108
* JavaScript-specific continuation implementation
109
*/
110
internal class ContinuationImpl<in T>(
111
completion: Continuation<Any?>?,
112
private val _context: CoroutineContext
113
) : Continuation<T>
114
115
/**
116
* Generator-based coroutine implementation for JavaScript
117
*/
118
internal class GeneratorCoroutineImpl<in T>(
119
private val resultContinuation: Continuation<T>
120
) : Continuation<Any?>
121
122
/**
123
* Safe continuation wrapper for JavaScript environments
124
*/
125
internal class SafeContinuation<in T> : Continuation<T>
126
```
127
128
### Coroutine Context
129
130
Context elements for coroutine execution.
131
132
```kotlin { .api }
133
/**
134
* Empty coroutine context
135
*/
136
object EmptyCoroutineContext : CoroutineContext {
137
override fun <E : CoroutineContext.Element> get(key: CoroutineContext.Key<E>): E? = null
138
override fun <R> fold(initial: R, operation: (R, CoroutineContext.Element) -> R): R = initial
139
override fun plus(context: CoroutineContext): CoroutineContext = context
140
override fun minusKey(key: CoroutineContext.Key<*>): CoroutineContext = this
141
}
142
143
/**
144
* Coroutine context interface
145
*/
146
interface CoroutineContext {
147
operator fun <E : Element> get(key: Key<E>): E?
148
fun <R> fold(initial: R, operation: (R, Element) -> R): R
149
operator fun plus(context: CoroutineContext): CoroutineContext
150
fun minusKey(key: Key<*>): CoroutineContext
151
152
interface Element : CoroutineContext
153
interface Key<E : Element>
154
}
155
```
156
157
**Usage Examples:**
158
159
```kotlin
160
import kotlin.coroutines.*
161
162
// Create coroutine with empty context
163
suspend fun simpleCoroutine(): Int {
164
return 42
165
}
166
167
// Custom continuation with context
168
val continuation = object : Continuation<Int> {
169
override val context: CoroutineContext = EmptyCoroutineContext
170
171
override fun resumeWith(result: Result<Int>) {
172
result.fold(
173
onSuccess = { value -> console.log("Got value: $value") },
174
onFailure = { error -> console.error("Error: $error") }
175
)
176
}
177
}
178
179
// Start coroutine
180
::simpleCoroutine.startCoroutineUninterceptedOrReturn(continuation)
181
```
182
183
## Types
184
185
```kotlin { .api }
186
// Core coroutine types
187
interface Continuation<in T> {
188
val context: CoroutineContext
189
fun resumeWith(result: Result<T>)
190
}
191
192
interface CoroutineContext {
193
operator fun <E : Element> get(key: Key<E>): E?
194
fun <R> fold(initial: R, operation: (R, Element) -> R): R
195
operator fun plus(context: CoroutineContext): CoroutineContext
196
fun minusKey(key: Key<*>): CoroutineContext
197
198
interface Element : CoroutineContext
199
interface Key<E : Element>
200
}
201
202
// Cancellation support
203
class CancellationException : IllegalStateException
204
205
// Context implementations
206
object EmptyCoroutineContext : CoroutineContext
207
208
// Internal implementation classes
209
internal class ContinuationImpl<in T> : Continuation<T>
210
internal class GeneratorCoroutineImpl<in T> : Continuation<Any?>
211
internal class SafeContinuation<in T> : Continuation<T>
212
213
// Result type for continuation resumption
214
class Result<out T> {
215
fun <R> fold(onSuccess: (T) -> R, onFailure: (Throwable) -> R): R
216
fun getOrThrow(): T
217
fun getOrNull(): T?
218
fun exceptionOrNull(): Throwable?
219
val isSuccess: Boolean
220
val isFailure: Boolean
221
}
222
```