CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core-iosx64

Kotlin coroutines library providing comprehensive asynchronous programming support with structured concurrency for iOS x64 platforms

Pending
Overview
Eval results
Files

coroutine-builders.mddocs/

Coroutine Builders

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.

Capabilities

Launch Builder

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
): Job

Usage 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()

Async Builder

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())
}

WithContext

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
): T

Usage 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
}

RunBlocking

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
): T

Usage 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()
    }
}

Producer (Channel Builder)

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")
    }
}

CoroutineStart Options

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 Comparison

BuilderReturnsUse CaseBlocking
launchJobFire-and-forget operationsNo
asyncDeferred<T>Concurrent computations with resultsNo
withContextTContext switching with resultSuspending
runBlockingTBridge to blocking codeYes
produceReceiveChannel<E>Value production over timeNo

Exception Handling in Builders

Different builders handle exceptions differently:

  • launch: Exceptions are handled by the parent's exception handler or crash the application
  • async: Exceptions are stored in the Deferred and re-thrown when await() is called
  • withContext: Exceptions propagate directly to the caller
  • runBlocking: Exceptions propagate to the calling thread
  • produce: Exceptions close the channel and propagate to consumers

This 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

docs

channels.md

coroutine-builders.md

coroutine-management.md

dispatchers.md

error-handling.md

flow-api.md

index.md

select-expression.md

synchronization.md

tile.json