Updated:
Apps constantly wait: for a network response, a database query, a file to download. If that waiting happens on the main thread, the app freezes. Coroutines let you write code that waits without blocking a thread, in plain top-to-bottom style, with no callbacks.
Setup
Coroutines live in the kotlinx-coroutines library. In an Android project it’s usually already there through the lifecycle libraries. Otherwise, add it to your module’s build.gradle.kts:
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") // check for the latest version
}Use kotlinx-coroutines-android in Android apps. To try the examples without a project, the Kotlin Playground already includes coroutines.
Your first coroutine
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000) // waits 1 second without blocking the thread
println("World!")
}
println("Hello,")
}Output:
Hello, World!
What happens:
runBlockingstarts a coroutine and waits until everything inside it has finished. It’s used inmainand in tests, not in Android UI code.launchstarts a new coroutine that runs alongside the rest of the code.delay(1000)suspends that coroutine for a second, so “Hello,” is printed first.
suspend functions
A suspend function can pause without blocking. It can only be called from a coroutine or from another suspend function:
import kotlinx.coroutines.*
suspend fun fetchUserName(id: Int): String {
delay(300) // pretend this is a network call
return "User #$id"
}
fun main() = runBlocking {
println("Loading…")
val name = fetchUserName(7) // looks like normal code
println("Loaded $name")
}Output:
Loading… Loaded User #7
The code reads top to bottom, like ordinary code, but while fetchUserName is waiting, the thread is free to do other work.
delay vs Thread.sleep
delay(ms) | Thread.sleep(ms) | |
|---|---|---|
| What it pauses | only this coroutine | the whole thread |
| Other coroutines on that thread | keep running | are stuck too |
| Use in coroutines | ✅ | ❌ |
launch: start and forget
launch returns a Job. You can wait for it with join() or stop it with cancel():
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(3) { i ->
println("Uploading part ${i + 1}")
delay(100)
}
}
job.join() // wait until it's done
println("Upload complete")
}Output:
Uploading part 1 Uploading part 2 Uploading part 3 Upload complete
async and await: get a result
async is like launch, but returns a Deferred<T>, a value you can await() later. Starting two async blocks runs them at the same time:
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun loadProfile(): String { delay(500); return "Profile" }
suspend fun loadOrders(): Int { delay(500); return 3 }
fun main() = runBlocking {
val time = measureTimeMillis {
val profile = async { loadProfile() }
val orders = async { loadOrders() }
println("${profile.await()} with ${orders.await()} orders")
}
println("Took about ${(time / 100) * 100} ms, not 1000")
}Output:
Profile with 3 orders Took about 500 ms, not 1000
Both loads wait half a second, but because they run together, the total is about 500 ms.
coroutineScope: structured concurrency
Coroutines started inside a scope belong to it. The scope doesn’t finish until all of its children finish, and if one child fails, the others are cancelled. This is called structured concurrency, and it means coroutines can’t leak:
import kotlinx.coroutines.*
suspend fun loadDashboard(): List<String> = coroutineScope {
val news = async { delay(200); "3 news" }
val weather = async { delay(100); "28°C" }
listOf(news.await(), weather.await())
}
fun main() = runBlocking {
println(loadDashboard())
}Output:
[3 news, 28°C]
Cancellation
import kotlinx.coroutines.*
fun main() = runBlocking {
val job = launch {
repeat(100) { i ->
println("Working $i")
delay(100)
}
}
delay(350)
job.cancel() // stop it
job.join()
println("Cancelled")
}Output:
Working 0 Working 1 Working 2 Working 3 Cancelled
delay and other suspend functions from the library check for cancellation automatically. In Android, viewModelScope and lifecycleScope cancel their coroutines for you when the screen goes away.
Coroutines in Android (preview)
class ProfileViewModel(private val repo: UserRepository) : ViewModel() {
fun load() {
viewModelScope.launch {
val user = repo.getUser() // suspend function
_state.value = UiState(user)
}
}
}The next lesson explains which thread this runs on, and how to move work to a background thread with dispatchers.
Common mistakes
- Using
runBlockingin app code: it blocks the thread, which defeats the purpose. UseviewModelScopeorlifecycleScope. - Using
GlobalScope: its coroutines aren’t tied to anything and can leak. Use a proper scope. - Calling
await()right after eachasync:async { a() }.await()thenasync { b() }.await()runs them one after another. Start both first, then await.
Exercise
Simulate downloading three files of different sizes at the same time, and print the total time and size.
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun download(name: String, ms: Long, sizeMb: Int): Int {
delay(ms)
println("$name done")
return sizeMb
}
fun main() = runBlocking {
val time = measureTimeMillis {
val sizes = listOf(
async { download("photo.jpg", 300, 4) },
async { download("video.mp4", 600, 120) },
async { download("notes.pdf", 100, 1) }
).awaitAll()
println("Total: ${sizes.sum()} MB")
}
println("Finished in about ${(time / 100) * 100} ms")
}Output:
notes.pdf done photo.jpg done video.mp4 done Total: 125 MB Finished in about 600 ms
The files finish in order of their wait time, and the total time is close to the longest one (600 ms), not the sum.
FAQ
What is a coroutine in Kotlin?
A lightweight piece of work that can pause and resume without blocking a thread. You can run thousands of them on a few threads.
What is the difference between launch and async?
launch starts a coroutine and returns a Job with no result. async returns a Deferred whose result you get with await().
What does suspend mean in Kotlin?
A suspend function can pause its coroutine (for example while waiting for the network) and resume later, without blocking the thread.
Keep reading


