Kotlin Coroutines — A Beginner-Friendly Introduction
Coroutines make asynchronous programming readable and safe. This beginner guide explains the core concepts with practical examples.
What You Will Learn
- What a coroutine is and why it helps
- How to use runBlocking and launch
- What suspend functions are
- How delay works without blocking threads
- Why coroutines are better than callbacks
What is a Coroutine?
Your First Coroutine
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000)
println("Coroutine finished")
}
println("Main continues")
}runBlocking creates a coroutine scope and blocks the current thread until all child coroutines finish. launch starts a new coroutine concurrently. delay(1000) suspends the coroutine for 1 second without blocking the thread.
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")suspend Functions
Writing a suspend Function
import kotlinx.coroutines.*
suspend fun fetchData(): String {
delay(500) // simulates network request
return "Data loaded"
}
fun main() = runBlocking {
val result = fetchData()
println(result)
}fetchData is a suspend function. delay inside it suspends the function, freeing the thread. When the delay is done, the function resumes and returns its result.
async and await
async and await Example
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")import kotlinx.coroutines.*
fun main() = runBlocking {
val result = async {
delay(500)
10 + 20
}
println(result.await())
}async returns a Deferred<Int>. await() suspends until the async block finishes and returns 30. The computation runs concurrently with other code.
Practice Exercise
What does this print, and in what order? import kotlinx.coroutines.* fun main() = runBlocking { launch { println("B") } println("A") }
Quick Quiz
What does delay() do in a Kotlin coroutine?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review