CtrlK
BlogDocsLog inGet started
Tessl Logo

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

JVM-specific implementation of kotlinx.coroutines core library providing coroutine primitives, builders, dispatchers, and synchronization primitives for asynchronous programming in Kotlin.

Pending
Overview
Eval results
Files

coroutine-builders.mddocs/

Coroutine Builders

Core functions for creating and launching coroutines with different execution patterns, lifecycle management, and cancellation behavior.

Capabilities

launch

Launches a new coroutine without blocking the current thread and returns a Job reference for lifecycle management.

/**
 * Launches a new coroutine without blocking the current thread
 * @param context additional coroutine context elements
 * @param start coroutine start option (DEFAULT, LAZY, ATOMIC, UNDISPATCHED)
 * @param block the coroutine code to execute
 * @return Job instance for cancellation and lifecycle management
 */
fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit
): Job

Usage Examples:

import kotlinx.coroutines.*

fun main() = runBlocking {
    // Basic launch
    val job = launch {
        delay(1000L)
        println("Coroutine completed")
    }
    
    // Launch with specific dispatcher
    val ioJob = launch(Dispatchers.IO) {
        performBlockingIO()
    }
    
    // Lazy launch - starts only when explicitly started or joined
    val lazyJob = launch(start = CoroutineStart.LAZY) {
        println("Lazy coroutine started")
    }
    lazyJob.start() // Explicitly start
    
    // Wait for all jobs
    job.join()
    ioJob.join()
    lazyJob.join()
}

async

Creates a coroutine that returns a future result as a Deferred, enabling concurrent computation with result retrieval.

/**
 * Creates a coroutine and returns its future result as Deferred
 * @param context additional coroutine context elements
 * @param start coroutine start option
 * @param block the coroutine code that produces a result
 * @return Deferred instance to await the result
 */
fun <T> CoroutineScope.async(
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T>

Usage Examples:

import kotlinx.coroutines.*

fun main() = runBlocking {
    // Concurrent async operations
    val deferred1 = async { computeValue1() }
    val deferred2 = async { computeValue2() }
    
    // Await results
    val result1 = deferred1.await()
    val result2 = deferred2.await()
    println("Results: $result1, $result2")
    
    // Async with different dispatcher
    val ioDeferred = async(Dispatchers.IO) {
        loadDataFromFile()
    }
    
    val data = ioDeferred.await()
    processData(data)
    
    // Multiple async operations
    val results = awaitAll(
        async { fetchUserData(1) },
        async { fetchUserData(2) },
        async { fetchUserData(3) }
    )
}

suspend fun computeValue1(): String {
    delay(100)
    return "Value 1"
}

suspend fun computeValue2(): String {
    delay(200)
    return "Value 2"
}

withContext

Switches to a different coroutine context, executes a block, and returns the result while preserving structured concurrency.

/**
 * Calls the specified suspending block with given coroutine context
 * @param context the context to switch to
 * @param block the suspending block to execute
 * @return the result of the block execution
 */
suspend fun <T> withContext(
    context: CoroutineContext,
    block: suspend CoroutineScope.() -> T
): T

Usage Examples:

import kotlinx.coroutines.*

suspend fun processData(): String = withContext(Dispatchers.Default) {
    // CPU-intensive computation on Default dispatcher
    (1..1000000).map { it * 2 }.sum().toString()
}

suspend fun readFile(filename: String): String = withContext(Dispatchers.IO) {
    // I/O operation on IO dispatcher
    java.io.File(filename).readText()
}

fun main() = runBlocking {
    // Context switching example
    println("Starting on: ${Thread.currentThread().name}")
    
    val result = withContext(Dispatchers.IO) {
        println("IO context: ${Thread.currentThread().name}")
        readFile("data.txt")
    }
    
    val processed = withContext(Dispatchers.Default) {
        println("Default context: ${Thread.currentThread().name}")
        result.uppercase()
    }
    
    println("Back to: ${Thread.currentThread().name}")
    println("Final result: $processed")
}

runBlocking (JVM-specific)

Blocks the current thread until the coroutine completes, bridging between blocking and non-blocking code.

/**
 * Runs coroutine and blocks current thread until completion
 * @param context the context for the coroutine
 * @param block the coroutine code to execute
 * @return the result of the coroutine execution
 */
fun <T> runBlocking(
    context: CoroutineContext = EmptyCoroutineContext,
    block: suspend CoroutineScope.() -> T
): T

Usage Examples:

import kotlinx.coroutines.*

// Main function - typical use case
fun main() = runBlocking {
    println("Starting application")
    
    launch {
        delay(1000L)
        println("Background task completed")
    }
    
    println("Application ready")
    delay(2000L)
    println("Application finished")
}

// Testing coroutines
class CoroutineTest {
    @Test
    fun testAsyncOperation() = runBlocking {
        val result = async {
            delay(100)
            "test result"
        }
        
        assertEquals("test result", result.await())
    }
}

// Bridging blocking and suspending code
fun blockingFunction(): String = runBlocking {
    val data = fetchDataSuspending()
    processData(data)
}

coroutineScope

Creates a new coroutine scope that inherits the context and ensures all child coroutines complete before returning.

/**
 * Creates a coroutine scope and suspends until all child coroutines complete
 * @param block the coroutine scope block to execute
 * @return the result of the block execution
 */
suspend fun <T> coroutineScope(
    block: suspend CoroutineScope.() -> T
): T

Usage Examples:

import kotlinx.coroutines.*

suspend fun processMultipleItems(items: List<String>): List<String> = coroutineScope {
    // All async operations must complete before returning
    items.map { item ->
        async {
            processItem(item)
        }
    }.awaitAll()
}

suspend fun complexOperation(): String = coroutineScope {
    val part1 = async { computePart1() }
    val part2 = async { computePart2() }
    val part3 = async { computePart3() }
    
    // If any child fails, all siblings are cancelled
    "${part1.await()}-${part2.await()}-${part3.await()}"
}

Types

CoroutineStart

Defines how a coroutine should be started.

enum class CoroutineStart {
    /** Start immediately according to its context */
    DEFAULT,
    /** Start lazily only when needed */
    LAZY,
    /** Start atomically (non-cancellably) according to its context */
    ATOMIC,
    /** Start immediately in the current thread until the first suspension */
    UNDISPATCHED
}

CoroutineScope

Interface defining a scope for launching coroutines with structured concurrency.

interface CoroutineScope {
    /** The context of this scope */
    val coroutineContext: CoroutineContext
}

/** Creates a new coroutine scope with given context */
fun CoroutineScope(context: CoroutineContext): CoroutineScope

/** Creates a new coroutine scope with a new Job */
fun MainScope(): CoroutineScope

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlinx--kotlinx-coroutines-core-jvm

docs

channels.md

coroutine-builders.md

dispatchers.md

exception-handling.md

flow-api.md

index.md

job-management.md

jvm-integration.md

synchronization.md

tile.json