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-management.mddocs/

Coroutine Management

Core lifecycle management for coroutines including Job interface, scoping, and structured concurrency support. This provides the foundation for all coroutine operations with automatic cleanup and cancellation propagation.

Capabilities

Job Interface

The fundamental interface for managing coroutine lifecycle with structured concurrency support.

/**
 * A background job that represents a coroutine
 */
interface Job : CoroutineContext.Element {
    /** Returns true when the job is active */
    val isActive: Boolean
    /** Returns true when the job has completed */
    val isCompleted: Boolean
    /** Returns true when the job was cancelled */
    val isCancelled: Boolean
    /** All direct children of this job */
    val children: Sequence<Job>
    /** Parent job of this job */
    val parent: Job?
    
    /** Start the job if it was created with CoroutineStart.LAZY */
    fun start(): Boolean
    /** Cancel the job with optional cause */
    fun cancel(cause: CancellationException? = null)
    /** Wait for the job to complete */
    suspend fun join()
    /** Install completion handler */
    fun invokeOnCompletion(handler: CompletionHandler): DisposableHandle
}

/**
 * A job that can be completed manually
 */
interface CompletableJob : Job {
    /** Complete the job successfully */
    fun complete(): Boolean
    /** Complete the job with exception */
    fun completeExceptionally(exception: Throwable): Boolean
}

/**
 * Factory function to create a Job
 */
fun Job(parent: Job? = null): CompletableJob

/**
 * Factory function to create a supervisor job
 */
fun SupervisorJob(parent: Job? = null): CompletableJob

Usage Examples:

import kotlinx.coroutines.*

// Create a job manually
val job = Job()

// Create a supervisor job (failures don't cancel siblings)
val supervisorJob = SupervisorJob()

// Launch a child job
val childJob = CoroutineScope(job).launch {
    delay(1000)
    println("Child completed")
}

// Cancel parent (cancels all children)
job.cancel()

// Wait for completion
childJob.join()

Deferred Interface

Job with result value for computations that produce results asynchronously.

/**
 * A Job that produces a result value
 */
interface Deferred<out T> : Job {
    /** Wait for completion and return the result */
    suspend fun await(): T
    /** Get completed result or throw if not completed */
    fun getCompleted(): T
    /** Get completion exception or null if completed successfully */
    fun getCompletionExceptionOrNull(): Throwable?
}

/**
 * A Deferred that can be completed manually
 */
interface CompletableDeferred<T> : Deferred<T>, CompletableJob {
    /** Complete with a value */
    fun complete(value: T): Boolean
}

/**
 * Factory function to create CompletableDeferred
 */
fun <T> CompletableDeferred(parent: Job? = null): CompletableDeferred<T>

Usage Examples:

import kotlinx.coroutines.*

// Create a CompletableDeferred
val deferred = CompletableDeferred<String>()

// Complete it from another coroutine
launch {
    delay(100)
    deferred.complete("Hello, World!")
}

// Await the result
val result = deferred.await()
println(result) // "Hello, World!"

CoroutineScope Interface

Defines a scope for new coroutines with structured concurrency and automatic cancellation.

/**
 * Defines a scope for new coroutines
 */
interface CoroutineScope {
    /** The context of this scope */
    val coroutineContext: CoroutineContext
}

/**
 * Factory function to create a CoroutineScope
 */
fun CoroutineScope(context: CoroutineContext): CoroutineScope

/**
 * Creates a MainScope for UI applications
 */
fun MainScope(): CoroutineScope

/**
 * Global scope for top-level coroutines (use with caution)
 */
object GlobalScope : CoroutineScope

Extension Properties and Functions:

/**
 * Returns true if the scope is active
 */
val CoroutineScope.isActive: Boolean

/**
 * Cancels the scope and all its children
 */
fun CoroutineScope.cancel(cause: CancellationException? = null)

/**
 * Ensures the scope is active or throws CancellationException
 */
fun CoroutineScope.ensureActive()

Usage Examples:

import kotlinx.coroutines.*

// Create a scope with specific context
val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())

// Launch coroutines in the scope
scope.launch {
    // This coroutine will be cancelled when scope is cancelled
    delay(1000)
    println("Coroutine completed")
}

// Check if scope is active
if (scope.isActive) {
    println("Scope is still active")
}

// Cancel the entire scope
scope.cancel()

Scoping Functions

Functions that create child scopes with structured concurrency.

/**
 * Creates a child scope and waits for all children to complete
 */
suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R

/**
 * Creates a supervisor scope where child failures don't affect siblings
 */
suspend fun <R> supervisorScope(block: suspend CoroutineScope.() -> R): R

/**
 * Returns the current coroutine context
 */
suspend fun currentCoroutineContext(): CoroutineContext

Usage Examples:

import kotlinx.coroutines.*

suspend fun parallelWork() = coroutineScope {
    // All launched coroutines are children of this scope
    val deferred1 = async { computeValue1() }
    val deferred2 = async { computeValue2() }
    
    // If any child fails, all siblings are cancelled
    val result1 = deferred1.await()
    val result2 = deferred2.await()
    
    result1 + result2
} // Function doesn't complete until all children complete

suspend fun supervisedWork() = supervisorScope {
    // Child failures don't cancel siblings
    val job1 = launch { riskyOperation1() }
    val job2 = launch { riskyOperation2() }
    
    // Both jobs run independently
    joinAll(job1, job2)
}

Completion Handlers

/**
 * Handler for job completion
 */
typealias CompletionHandler = (cause: Throwable?) -> Unit

/**
 * Handle for disposing completion handlers
 */
interface DisposableHandle {
    /** Dispose the handle */
    fun dispose()
}

Context Elements

Core context elements for coroutine configuration.

/**
 * Debugging name for coroutines
 */
data class CoroutineName(val name: String) : CoroutineContext.Element {
    companion object Key : CoroutineContext.Key<CoroutineName>
}

/**
 * Non-cancellable context for cleanup operations
 */
object NonCancellable : CoroutineContext.Element, Job {
    override val isActive: Boolean get() = true
    override val isCompleted: Boolean get() = false
    override val isCancelled: Boolean get() = false
    // ... other Job methods that are no-ops
}

Usage Examples:

import kotlinx.coroutines.*

// Name coroutines for debugging
launch(CoroutineName("background-task")) {
    // This coroutine will appear as "background-task" in debugging
    delay(1000)
}

// Use NonCancellable for cleanup
try {
    riskyOperation()
} finally {
    withContext(NonCancellable) {
        // This cleanup code won't be cancelled
        cleanupResources()
    }
}

Job Hierarchy and Cancellation

The Job interface establishes parent-child relationships that form a hierarchy:

  1. Parent-Child Relationship: When a Job is used as a parent context for launching coroutines, those coroutines become children
  2. Cancellation Propagation: Cancelling a parent job cancels all its children
  3. Completion Waiting: A parent job waits for all children to complete before completing itself
  4. Exception Propagation: By default, child exceptions cancel the parent and all siblings

This hierarchy ensures structured concurrency where resource cleanup and cancellation are handled automatically.

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