BudiBadu Logo
Samplebadu

Kotlin by Example: Coroutines

Kotlin 1.9+

Asynchronous programming made simple with this sample code demonstrating coroutine launch with runBlocking, suspend functions for pausable execution, delay for non-blocking waits, and lightweight concurrency without thread blocking.

Code

import kotlinx.coroutines.*

fun main() = runBlocking {
    // Launch a new coroutine in the background
    launch {
        delay(1000L) // Non-blocking delay
        println("World!")
    }
    
    println("Hello,")
    
    // The main coroutine continues while the child works
    // runBlocking waits for all children to finish
}

// Suspending function
suspend fun doWork() {
    delay(500L)
    println("Work done")
}

Explanation

Kotlin coroutines provide a solution for asynchronous programming, allowing code to suspend execution without blocking threads. Coroutines are lightweight alternatives to threads, consuming fewer resources and enabling thousands of concurrent coroutines on a single thread. The core concept involves suspend functions which can pause and resume execution later without blocking the underlying thread.

Coroutine builders like launch() for fire-and-forget operations and async() for returning results start new coroutines within a CoroutineScope that manages their lifecycle. The runBlocking builder creates a scope and blocks the current thread until all coroutines inside complete, primarily used in main functions and tests to bridge blocking and non-blocking code.

The delay() function is a suspend function that pauses the coroutine for a specified time without blocking the thread, freeing it to execute other coroutines. This differs fundamentally from Thread.sleep() which blocks the entire thread. The kotlinx.coroutines library provides features for launching coroutines, managing concurrency, structured concurrency with scopes, and working with asynchronous streams like Flow.

Code Breakdown

3
runBlocking creates scope, blocks main thread until children finish.
5
launch starts new coroutine for fire-and-forget execution.
6
delay(1000L) suspends coroutine without blocking thread.
17
suspend fun declares function that can pause execution.