Kotlin coroutines library providing comprehensive asynchronous programming support with structured concurrency for iOS x64 platforms
—
Functions for creating and launching coroutines with different execution patterns and result handling. These builders provide the primary means of starting concurrent operations within coroutine scopes.
Fire-and-forget coroutine that returns a Job for lifecycle management.
/**
* Launches a new coroutine without blocking the current thread
* @param context additional context elements for the coroutine
* @param start coroutine start option (DEFAULT, LAZY, ATOMIC, UNDISPATCHED)
* @param block the coroutine code
* @return Job representing the coroutine
*/
fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): JobUsage Examples:
import kotlinx.coroutines.*
val scope = CoroutineScope(Dispatchers.Default)
// Basic launch
val job = scope.launch {
delay(1000)
println("Task completed")
}
// Launch with custom context
val jobWithContext = scope.launch(Dispatchers.IO + CoroutineName("file-processor")) {
// Runs on IO dispatcher with debug name
processFile()
}
// Lazy launch (starts when job.start() is called or join() is awaited)
val lazyJob = scope.launch(start = CoroutineStart.LAZY) {
expensiveComputation()
}
lazyJob.start() // Explicitly start the coroutine
// Wait for completion
job.join()Concurrent computation that returns a Deferred with a result value.
/**
* Creates a coroutine that computes a value concurrently
* @param context additional context elements for the coroutine
* @param start coroutine start option
* @param block the coroutine code that returns a value
* @return Deferred representing the future result
*/
fun <T> CoroutineScope.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T>Usage Examples:
import kotlinx.coroutines.*
suspend fun concurrentComputation() {
val scope = CoroutineScope(Dispatchers.Default)
// Launch multiple async computations
val deferred1 = scope.async { computeValue1() }
val deferred2 = scope.async { computeValue2() }
val deferred3 = scope.async { computeValue3() }
// Wait for all results
val result1 = deferred1.await()
val result2 = deferred2.await()
val result3 = deferred3.await()
println("Results: $result1, $result2, $result3")
}
// Async with custom context
suspend fun asyncWithContext() = coroutineScope {
val networkCall = async(Dispatchers.IO) {
fetchDataFromNetwork()
}
val localData = async(Dispatchers.Default) {
processLocalData()
}
// Combine results
CombinedResult(networkCall.await(), localData.await())
}Context switching function that executes a block in a different context and returns the result.
/**
* Calls the specified block with the given coroutine context
* @param context the new context for the block
* @param block the code to execute in the new context
* @return the result of the block
*/
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): TUsage Examples:
import kotlinx.coroutines.*
suspend fun processData() {
// Switch to IO context for file operations
val fileContent = withContext(Dispatchers.IO) {
readFileContent("data.txt")
}
// Switch to Default context for computation
val processedData = withContext(Dispatchers.Default) {
heavyProcessing(fileContent)
}
// Switch to Main context for UI updates (if available)
withContext(Dispatchers.Main) {
updateUI(processedData)
}
}
// WithContext with timeout
suspend fun fetchWithTimeout() {
val result = withContext(Dispatchers.IO) {
withTimeout(5000) {
fetchDataFromServer()
}
}
return result
}Blocking bridge between regular and suspend functions (platform-specific availability).
/**
* Runs a new coroutine and blocks the current thread until completion
* @param context the context for the new coroutine
* @param block the coroutine code
* @return the result of the coroutine
*/
fun <T> runBlocking(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> T
): TUsage Examples:
import kotlinx.coroutines.*
// In main function or tests
fun main() = runBlocking {
launch {
delay(1000)
println("World!")
}
println("Hello,")
delay(2000)
}
// In tests
@Test
fun testCoroutine() = runBlocking {
val result = async { computeAsync() }
assertEquals(42, result.await())
}
// Bridge to suspend functions
fun synchronousFunction(): String {
return runBlocking {
suspendingFunction()
}
}Creates a receive channel from a coroutine that produces values.
/**
* Creates a coroutine that produces values and sends them to a channel
* @param context additional context elements
* @param capacity channel capacity
* @param block the producer coroutine code
* @return ReceiveChannel to consume produced values
*/
fun <E> CoroutineScope.produce(
context: CoroutineContext = EmptyCoroutineContext,
capacity: Int = 0,
block: suspend ProducerScope<E>.() -> Unit
): ReceiveChannel<E>
/**
* Scope for the producer coroutine
*/
interface ProducerScope<in E> : CoroutineScope, SendChannel<E>Usage Examples:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
suspend fun numberProducer() {
val numbers = produce {
for (i in 1..10) {
send(i * i) // Send squares
delay(100) // Simulate work
}
}
// Consume the numbers
for (number in numbers) {
println("Received: $number")
}
}
// Producer with custom capacity
suspend fun bufferedProducer() {
val channel = produce(capacity = 5) {
repeat(20) { i ->
send("Item $i")
println("Sent item $i")
}
}
// Consumer can lag behind due to buffering
for (item in channel) {
delay(200) // Slow consumer
println("Received: $item")
}
}Configuration for how coroutines are started.
/**
* Defines options for starting coroutines
*/
enum class CoroutineStart {
/** Start coroutine immediately in the current thread until first suspension */
DEFAULT,
/** Start coroutine lazily when start() or join() is called */
LAZY,
/** Start coroutine atomically - cannot be cancelled until it starts */
ATOMIC,
/** Start coroutine immediately in the current thread */
UNDISPATCHED
}Usage Examples:
import kotlinx.coroutines.*
suspend fun startOptions() = coroutineScope {
// Default: scheduled immediately, suspends at first suspension point
val defaultJob = launch(start = CoroutineStart.DEFAULT) {
delay(100)
println("Default started")
}
// Lazy: doesn't start until explicitly started
val lazyJob = launch(start = CoroutineStart.LAZY) {
println("Lazy started")
}
// Atomic: cannot be cancelled before it starts running
val atomicJob = launch(start = CoroutineStart.ATOMIC) {
println("Atomic started")
}
// Undispatched: runs immediately in current thread until first suspension
val undispatchedJob = launch(start = CoroutineStart.UNDISPATCHED) {
println("Undispatched runs immediately")
delay(1) // Now it gets dispatched
println("After suspension")
}
// Start the lazy job
lazyJob.start()
// Wait for all
joinAll(defaultJob, lazyJob, atomicJob, undispatchedJob)
}| Builder | Returns | Use Case | Blocking |
|---|---|---|---|
launch | Job | Fire-and-forget operations | No |
async | Deferred<T> | Concurrent computations with results | No |
withContext | T | Context switching with result | Suspending |
runBlocking | T | Bridge to blocking code | Yes |
produce | ReceiveChannel<E> | Value production over time | No |
Different builders handle exceptions differently:
await() is calledThis makes async safe for operations that might fail, as exceptions don't crash the parent scope until explicitly checked with await().
Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core-iosx64