Kotlin Coroutines

Coroutines let you write asynchronous code that reads like synchronous code — no callback hell, no reactive chains.

Basic Coroutine

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000)
        println("World!")
    }
    println("Hello,")
}
// Output: Hello, (then) World!

Suspending Functions

Kotlin
suspend fun fetchUser(): String {
    delay(2000)  // non-blocking sleep
    return "Sita"
}

fun main() = runBlocking {
    val user = fetchUser()  // suspends, doesn't block thread
    println(user)
}

Parallel Execution

Kotlin
fun main() = runBlocking {
    val user = async { fetchUser() }
    val posts = async { fetchPosts() }

    println("User: ${user.await()}")
    println("Posts: ${posts.await()}")
}

Exception Handling

Kotlin
fun main() = runBlocking {
    try {
        val result = withContext(Dispatchers.IO) {
            fetchFromApi()
        }
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}

Tips

  • Use suspend for functions that may block.
  • Use async for parallel independent operations.
  • Coroutines are lightweight — you can launch thousands.

Next: sealed-classes.