or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

channels.mdcoroutine-builders.mddispatchers.mdexception-handling.mdflow-api.mdindex.mdjobs-deferreds.mdstructured-concurrency.mdsynchronization.md
tile.json

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

Coroutines support libraries for Kotlin providing structured concurrency primitives, Flow API for reactive streams, channels for communication, and synchronization utilities across all Kotlin platforms

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.jetbrains.kotlinx/kotlinx-coroutines-core@1.10.x

To install, run

npx @tessl/cli install tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core@1.10.0

index.mddocs/

kotlinx-coroutines-core

kotlinx-coroutines-core is the foundational library for structured concurrency in Kotlin, providing comprehensive asynchronous programming capabilities. It offers coroutine builders, Flow API for reactive streams, channels for communication between coroutines, and synchronization primitives for concurrent programming across all Kotlin platforms.

Package Information

  • Package Name: kotlinx-coroutines-core
  • Package Type: maven
  • Language: Kotlin
  • Platform: Kotlin Multiplatform (JVM, Android, JS, Native)
  • Installation: Add implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") to your Gradle dependencies

Core Imports

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.sync.*

For specific functionality:

// Core coroutine builders and scope
import kotlinx.coroutines.launch
import kotlinx.coroutines.async
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

// Flow API
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.MutableStateFlow

// Channels
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.produce

// Dispatchers
import kotlinx.coroutines.Dispatchers

Basic Usage

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

// Create a coroutine scope
val scope = MainScope()

// Launch a fire-and-forget coroutine
val job = scope.launch {
    delay(1000)
    println("Coroutine completed!")
}

// Launch a coroutine that returns a result
val deferred = scope.async {
    delay(500)
    "Hello from async!"
}

// Create and collect a Flow
val numberFlow = flow {
    for (i in 1..5) {
        emit(i)
        delay(100)
    }
}

scope.launch {
    numberFlow.collect { value ->
        println("Received: $value")
    }
}

// Wait for results
scope.launch {
    val result = deferred.await()
    println(result)
}

Architecture

kotlinx-coroutines-core is built around several key architectural components:

  • Structured Concurrency: Jobs form parent-child hierarchies where cancellation propagates automatically
  • Coroutine Contexts: Composable context elements (dispatchers, jobs, exception handlers) that define execution environment
  • Suspend Functions: Functions that can pause execution without blocking threads
  • Dispatchers: Thread pools and execution contexts for running coroutines
  • Flow API: Cold streams for reactive programming with rich operator support
  • Channel API: Hot communication primitives for producer-consumer patterns
  • Cancellation Model: Cooperative cancellation system with structured cleanup

Capabilities

Coroutine Builders and Scope Management

Core building blocks for creating and managing coroutines with structured concurrency guarantees.

interface CoroutineScope {
    val coroutineContext: CoroutineContext
}

fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T>

fun CoroutineScope(context: CoroutineContext): CoroutineScope
fun MainScope(): CoroutineScope

Coroutine Builders and Scopes

Job and Deferred Management

Lifecycle management for coroutines including cancellation, completion tracking, and result handling.

interface Job : CoroutineContext.Element {
    val isActive: Boolean
    val isCompleted: Boolean
    val isCancelled: Boolean
    val children: Sequence<Job>
    
    fun start(): Boolean
    fun cancel(cause: CancellationException? = null)
    suspend fun join()
}

interface Deferred<out T> : Job {
    suspend fun await(): T
    fun getCompleted(): T
    val onAwait: SelectClause1<T>
}

interface CompletableJob : Job {
    fun complete(): Boolean
    fun completeExceptionally(exception: Throwable): Boolean
}

Jobs and Deferreds

Coroutine Dispatchers

Thread management and execution contexts for controlling where coroutines run.

abstract class CoroutineDispatcher : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
    abstract fun dispatch(context: CoroutineContext, block: Runnable)
    open fun isDispatchNeeded(context: CoroutineContext): Boolean
    fun limitedParallelism(parallelism: Int): CoroutineDispatcher
}

object Dispatchers {
    val Default: CoroutineDispatcher
    val Main: MainCoroutineDispatcher
    val Unconfined: CoroutineDispatcher
}

abstract class MainCoroutineDispatcher : CoroutineDispatcher() {
    abstract val immediate: MainCoroutineDispatcher
}

Dispatchers

Flow API - Reactive Streams

Asynchronous data streams with rich operator support for reactive programming patterns.

interface Flow<out T> {
    suspend fun collect(collector: FlowCollector<T>)
}

interface FlowCollector<in T> {
    suspend fun emit(value: T)
}

interface StateFlow<out T> : SharedFlow<T> {
    val value: T
}

interface MutableStateFlow<T> : StateFlow<T>, MutableSharedFlow<T> {
    override var value: T
    fun compareAndSet(expect: T, update: T): Boolean
}

fun <T> MutableStateFlow<T>.update(function: (T) -> T)
fun <T> MutableStateFlow<T>.updateAndGet(function: (T) -> T): T
fun <T> MutableStateFlow<T>.getAndUpdate(function: (T) -> T): T

interface SharedFlow<out T> : Flow<T> {
    val replayCache: List<T>
    val subscriptionCount: StateFlow<Int>
}

interface MutableSharedFlow<T> : SharedFlow<T>, FlowCollector<T> {
    fun tryEmit(value: T): Boolean
    fun resetReplayCache()
}

Flow API

Channel API - Communication Primitives

Producer-consumer communication channels for passing data between coroutines.

interface Channel<E> : SendChannel<E>, ReceiveChannel<E>

interface SendChannel<in E> {
    val isClosedForSend: Boolean
    suspend fun send(element: E)
    fun trySend(element: E): ChannelResult<Unit>
    fun close(cause: Throwable? = null): Boolean
}

interface ReceiveChannel<out E> {
    val isClosedForReceive: Boolean
    suspend fun receive(): E
    fun tryReceive(): ChannelResult<E>
    fun cancel(cause: CancellationException? = null)
}

fun <E> Channel(
    capacity: Int = Channel.RENDEZVOUS,
    onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND,
    onUndeliveredElement: ((E) -> Unit)? = null
): Channel<E>

Channels

Synchronization Primitives

Thread-safe synchronization utilities for coordinating access to shared resources.

interface Mutex {
    val isLocked: Boolean
    suspend fun lock(owner: Any? = null)
    fun tryLock(owner: Any? = null): Boolean
    fun unlock(owner: Any? = null)
    suspend fun <T> withLock(owner: Any? = null, action: suspend () -> T): T
}

interface Semaphore {
    val availablePermits: Int
    suspend fun acquire()
    fun tryAcquire(): Boolean
    fun release()
    suspend fun <T> withPermit(action: suspend () -> T): T
}

fun Mutex(locked: Boolean = false): Mutex
fun Semaphore(permits: Int, acquiredPermits: Int = 0): Semaphore

Synchronization

Structured Concurrency Functions

Scoping functions and cancellation management for coordinated lifecycle management.

suspend fun <T> coroutineScope(block: suspend CoroutineScope.() -> T): T
suspend fun <T> supervisorScope(block: suspend CoroutineScope.() -> T): T
suspend fun <T> withContext(context: CoroutineContext, block: suspend CoroutineScope.() -> T): T
suspend fun <T> withTimeout(timeoutMillis: Long, block: suspend CoroutineScope.() -> T): T
suspend fun <T> withTimeoutOrNull(timeoutMillis: Long, block: suspend CoroutineScope.() -> T): T?

suspend fun delay(timeMillis: Long)
suspend fun delay(duration: Duration)
suspend fun yield()
suspend fun awaitCancellation(): Nothing
suspend fun currentCoroutineContext(): CoroutineContext
fun CoroutineContext.ensureActive()

Structured Concurrency

Select Expressions

Advanced multiplexing primitive for waiting on multiple suspending operations simultaneously.

suspend fun <R> select(builder: SelectBuilder<R>.() -> Unit): R
suspend fun <R> selectUnbiased(builder: SelectBuilder<R>.() -> Unit): R

interface SelectBuilder<in R> {
    fun onTimeout(timeMillis: Long, block: suspend () -> R)
}

// Select clauses available on various types
val Job.onJoin: SelectClause0
val <T> Deferred<T>.onAwait: SelectClause1<T>
val <E> SendChannel<E>.onSend: SelectClause2<E, SendChannel<E>>
val <E> ReceiveChannel<E>.onReceive: SelectClause1<E>
val <E> ReceiveChannel<E>.onReceiveCatching: SelectClause1<ChannelResult<E>>

Exception Handling and Cancellation

Comprehensive error handling and cancellation mechanisms for robust coroutine applications.

interface CoroutineExceptionHandler : CoroutineContext.Element {
    fun handleException(context: CoroutineContext, exception: Throwable)
}

open class CancellationException(message: String? = null, cause: Throwable? = null) : IllegalStateException(message, cause)
class TimeoutCancellationException(message: String?, coroutine: Job) : CancellationException(message)

object NonCancellable : AbstractCoroutineContextElement(Job), Job
fun SupervisorJob(parent: Job? = null): CompletableJob

Exception Handling

Types

Core Context Types

enum class CoroutineStart {
    DEFAULT, LAZY, ATOMIC, UNDISPATCHED
}

data class CoroutineName(val name: String) : AbstractCoroutineContextElement(CoroutineName)

enum class BufferOverflow {
    SUSPEND, DROP_OLDEST, DROP_LATEST
}

object GlobalScope : CoroutineScope {
    override val coroutineContext: CoroutineContext
}

// Select clause interfaces
interface SelectClause0
interface SelectClause1<out T>
interface SelectClause2<in P, out T>

// Duration support
typealias Duration = kotlin.time.Duration

Flow Sharing Configuration

interface SharingStarted {
    companion object {
        val Eagerly: SharingStarted
        val Lazily: SharingStarted
        fun WhileSubscribed(
            stopTimeoutMillis: Long = Long.MAX_VALUE,
            replayExpirationMillis: Long = Long.MAX_VALUE
        ): SharingStarted
    }
}

Channel Configuration

object Channel {
    const val RENDEZVOUS = 0
    const val CONFLATED = -1
    const val UNLIMITED = Int.MAX_VALUE
    const val BUFFERED = -2
    const val CHANNEL_DEFAULT_CAPACITY = 64
}

value class ChannelResult<out T> {
    val isSuccess: Boolean
    val isClosed: Boolean
    val isFailure: Boolean
    
    fun getOrNull(): T?
    fun exceptionOrNull(): Throwable?
}