0
# Coroutine Builders
1
2
Core functions for creating and launching coroutines with different execution patterns, lifecycle management, and cancellation behavior.
3
4
## Capabilities
5
6
### launch
7
8
Launches a new coroutine without blocking the current thread and returns a Job reference for lifecycle management.
9
10
```kotlin { .api }
11
/**
12
* Launches a new coroutine without blocking the current thread
13
* @param context additional coroutine context elements
14
* @param start coroutine start option (DEFAULT, LAZY, ATOMIC, UNDISPATCHED)
15
* @param block the coroutine code to execute
16
* @return Job instance for cancellation and lifecycle management
17
*/
18
fun CoroutineScope.launch(
19
context: CoroutineContext = EmptyCoroutineContext,
20
start: CoroutineStart = CoroutineStart.DEFAULT,
21
block: suspend CoroutineScope.() -> Unit
22
): Job
23
```
24
25
**Usage Examples:**
26
27
```kotlin
28
import kotlinx.coroutines.*
29
30
fun main() = runBlocking {
31
// Basic launch
32
val job = launch {
33
delay(1000L)
34
println("Coroutine completed")
35
}
36
37
// Launch with specific dispatcher
38
val ioJob = launch(Dispatchers.IO) {
39
performBlockingIO()
40
}
41
42
// Lazy launch - starts only when explicitly started or joined
43
val lazyJob = launch(start = CoroutineStart.LAZY) {
44
println("Lazy coroutine started")
45
}
46
lazyJob.start() // Explicitly start
47
48
// Wait for all jobs
49
job.join()
50
ioJob.join()
51
lazyJob.join()
52
}
53
```
54
55
### async
56
57
Creates a coroutine that returns a future result as a Deferred, enabling concurrent computation with result retrieval.
58
59
```kotlin { .api }
60
/**
61
* Creates a coroutine and returns its future result as Deferred
62
* @param context additional coroutine context elements
63
* @param start coroutine start option
64
* @param block the coroutine code that produces a result
65
* @return Deferred instance to await the result
66
*/
67
fun <T> CoroutineScope.async(
68
context: CoroutineContext = EmptyCoroutineContext,
69
start: CoroutineStart = CoroutineStart.DEFAULT,
70
block: suspend CoroutineScope.() -> T
71
): Deferred<T>
72
```
73
74
**Usage Examples:**
75
76
```kotlin
77
import kotlinx.coroutines.*
78
79
fun main() = runBlocking {
80
// Concurrent async operations
81
val deferred1 = async { computeValue1() }
82
val deferred2 = async { computeValue2() }
83
84
// Await results
85
val result1 = deferred1.await()
86
val result2 = deferred2.await()
87
println("Results: $result1, $result2")
88
89
// Async with different dispatcher
90
val ioDeferred = async(Dispatchers.IO) {
91
loadDataFromFile()
92
}
93
94
val data = ioDeferred.await()
95
processData(data)
96
97
// Multiple async operations
98
val results = awaitAll(
99
async { fetchUserData(1) },
100
async { fetchUserData(2) },
101
async { fetchUserData(3) }
102
)
103
}
104
105
suspend fun computeValue1(): String {
106
delay(100)
107
return "Value 1"
108
}
109
110
suspend fun computeValue2(): String {
111
delay(200)
112
return "Value 2"
113
}
114
```
115
116
### withContext
117
118
Switches to a different coroutine context, executes a block, and returns the result while preserving structured concurrency.
119
120
```kotlin { .api }
121
/**
122
* Calls the specified suspending block with given coroutine context
123
* @param context the context to switch to
124
* @param block the suspending block to execute
125
* @return the result of the block execution
126
*/
127
suspend fun <T> withContext(
128
context: CoroutineContext,
129
block: suspend CoroutineScope.() -> T
130
): T
131
```
132
133
**Usage Examples:**
134
135
```kotlin
136
import kotlinx.coroutines.*
137
138
suspend fun processData(): String = withContext(Dispatchers.Default) {
139
// CPU-intensive computation on Default dispatcher
140
(1..1000000).map { it * 2 }.sum().toString()
141
}
142
143
suspend fun readFile(filename: String): String = withContext(Dispatchers.IO) {
144
// I/O operation on IO dispatcher
145
java.io.File(filename).readText()
146
}
147
148
fun main() = runBlocking {
149
// Context switching example
150
println("Starting on: ${Thread.currentThread().name}")
151
152
val result = withContext(Dispatchers.IO) {
153
println("IO context: ${Thread.currentThread().name}")
154
readFile("data.txt")
155
}
156
157
val processed = withContext(Dispatchers.Default) {
158
println("Default context: ${Thread.currentThread().name}")
159
result.uppercase()
160
}
161
162
println("Back to: ${Thread.currentThread().name}")
163
println("Final result: $processed")
164
}
165
```
166
167
### runBlocking (JVM-specific)
168
169
Blocks the current thread until the coroutine completes, bridging between blocking and non-blocking code.
170
171
```kotlin { .api }
172
/**
173
* Runs coroutine and blocks current thread until completion
174
* @param context the context for the coroutine
175
* @param block the coroutine code to execute
176
* @return the result of the coroutine execution
177
*/
178
fun <T> runBlocking(
179
context: CoroutineContext = EmptyCoroutineContext,
180
block: suspend CoroutineScope.() -> T
181
): T
182
```
183
184
**Usage Examples:**
185
186
```kotlin
187
import kotlinx.coroutines.*
188
189
// Main function - typical use case
190
fun main() = runBlocking {
191
println("Starting application")
192
193
launch {
194
delay(1000L)
195
println("Background task completed")
196
}
197
198
println("Application ready")
199
delay(2000L)
200
println("Application finished")
201
}
202
203
// Testing coroutines
204
class CoroutineTest {
205
@Test
206
fun testAsyncOperation() = runBlocking {
207
val result = async {
208
delay(100)
209
"test result"
210
}
211
212
assertEquals("test result", result.await())
213
}
214
}
215
216
// Bridging blocking and suspending code
217
fun blockingFunction(): String = runBlocking {
218
val data = fetchDataSuspending()
219
processData(data)
220
}
221
```
222
223
### coroutineScope
224
225
Creates a new coroutine scope that inherits the context and ensures all child coroutines complete before returning.
226
227
```kotlin { .api }
228
/**
229
* Creates a coroutine scope and suspends until all child coroutines complete
230
* @param block the coroutine scope block to execute
231
* @return the result of the block execution
232
*/
233
suspend fun <T> coroutineScope(
234
block: suspend CoroutineScope.() -> T
235
): T
236
```
237
238
**Usage Examples:**
239
240
```kotlin
241
import kotlinx.coroutines.*
242
243
suspend fun processMultipleItems(items: List<String>): List<String> = coroutineScope {
244
// All async operations must complete before returning
245
items.map { item ->
246
async {
247
processItem(item)
248
}
249
}.awaitAll()
250
}
251
252
suspend fun complexOperation(): String = coroutineScope {
253
val part1 = async { computePart1() }
254
val part2 = async { computePart2() }
255
val part3 = async { computePart3() }
256
257
// If any child fails, all siblings are cancelled
258
"${part1.await()}-${part2.await()}-${part3.await()}"
259
}
260
```
261
262
## Types
263
264
### CoroutineStart
265
266
Defines how a coroutine should be started.
267
268
```kotlin { .api }
269
enum class CoroutineStart {
270
/** Start immediately according to its context */
271
DEFAULT,
272
/** Start lazily only when needed */
273
LAZY,
274
/** Start atomically (non-cancellably) according to its context */
275
ATOMIC,
276
/** Start immediately in the current thread until the first suspension */
277
UNDISPATCHED
278
}
279
```
280
281
### CoroutineScope
282
283
Interface defining a scope for launching coroutines with structured concurrency.
284
285
```kotlin { .api }
286
interface CoroutineScope {
287
/** The context of this scope */
288
val coroutineContext: CoroutineContext
289
}
290
291
/** Creates a new coroutine scope with given context */
292
fun CoroutineScope(context: CoroutineContext): CoroutineScope
293
294
/** Creates a new coroutine scope with a new Job */
295
fun MainScope(): CoroutineScope
296
```