1. Two ways to start coroutines
When you first see coroutines, you really want to ask: “OK, I got suspend and delay. But how do I make several things happen at the same time?” And this is where the two heroes of the day appear: launch and async. They both start a coroutine, but with different intentions: one is “do an action”, the other is “compute a result”. And when the intention reads correctly in code, your brain suffers less.
It’s important to lock this in: both launch and async are “coroutine builders” from kotlinx.coroutines. Kotlin documentation describes this directly: coroutines are started by builders like .launch() and .async(), and these are extensions on CoroutineScope (meaning you can call them “inside a coroutine environment”, for example inside runBlocking).
2. launch: starting a coroutine for actions
Imagine you hired a courier. You don’t need them to return a “number” or a “string” — you need them to go and do: deliver a package, press a button, print a log, send an email. That’s launch: “start a coroutine for a side effect”. Usually this is println, writing to a file, sending an event, updating state — that is, an action, not computing a value.
Let’s start with a tiny example: we start two coroutines that print strings with different delays.
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch {
delay(100)
println("L1 done") // L1 done
}
launch {
delay(50)
println("L2 done") // L2 done
}
println("Main continues") // Main continues
}
Here it’s very important to be mentally prepared: the Main continues line usually prints first, and L2 done appears before L1 done, because the delay is smaller. In other words, the order is not “top to bottom”, but “whoever made it in time” — and that’s not a bug; that’s the whole point.
Notice one more thing: launch doesn’t return anything as a “computation result”. Technically, it returns a Job, but today we won’t make that a separate topic (managing coroutine lifecycles is a different conversation). The main point: launch is about an action, so its “result” contract is not an Int/String.
Concurrency vs. parallelism
Now comes an important philosophical minute in 40–60 words; I promise, without being boring. When you start two coroutines via launch, you don’t have to get “true parallelism” (like two people lifting two different couches at the same time). You get concurrency: tasks can interleave, wait, “yield” to others. That already gives you wins in waiting and code ergonomics — and that’s why we’re here.
You can draw a simple time diagram (simplified):
sequenceDiagram
participant M as runBlocking/main
participant A as launch #1
participant B as launch #2
M->>A: start
M->>B: start
M->>M: println("Main continues")
A->>A: delay(100)
B->>B: delay(50)
B-->>M: println("L2 done")
A-->>M: println("L1 done")
3. async: a coroutine that promises a result
Now imagine not a courier, but a friend who’s good at math (everyone should have a friend like that… at least a virtual one). You ask: “Calculate the sum of taxes for me” or “Collect some statistics”. You don’t want just the “fact of an action”; you want a value. That’s what async is for.
async { ... } starts a coroutine and returns an object of type Deferred<T>. Read it like this: “a deferred result of type T”. As if you were handed a ticket: “the result will be later; here’s your number”.
Why this matters: you can start several computations, and then collect the results at a convenient moment.
Kotlin documentation says that coroutine builders like .async() are used to start coroutines the same way as .launch(), and they work within a CoroutineScope.
4. Deferred<T> and await(): “promise” and “getting it”
At this point, beginners often make the same mistake: they think Deferred<Int> is already an Int. No. It’s a “waiting container”. To get the real value, you must call await(). And await() is a suspend operation, because it can wait.
First, I’ll show the “obvious trap” — so you see it once and never step on it again.
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val d = async { 1 + 2 }
println(d) // DeferredCoroutine{Active}@...
println(d.await()) // 3
}
Here println(d) prints not 3, but the internal description of the Deferred object. But d.await() returns the result.
And let’s add a small analogy, without extra poetry. Deferred<T> is like a receipt from a cafe: you paid (started the computation), the receipt is in your hand, and the burger (T) will be brought a bit later. await() is like walking up to the counter and saying: “I’m here for my order; here’s the receipt.”
5. Pattern: several async, then await()
Now we’re getting to the main practical “trick” of async: you start several tasks, without awaiting immediately, and then collect the results. This matters because if you do await() right after each async, you can accidentally turn everything back into sequential execution.
Let’s compare two approaches. First, the “unsuccessful” one (in terms of concurrency): start and immediately wait.
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val a = async { delay(100); 10 }.await()
val b = async { delay(100); 32 }.await()
println(a + b) // 42
}
This works, but the logic is: wait for a, then start b. Sometimes that’s fine, but often you wanted something else.
Now, the “more correct for parallel waiting” approach: start first, then wait.
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val a = async { delay(100); 10 }
val b = async { delay(100); 32 }
println(a.await() + b.await()) // 42
}
Here both tasks start immediately, and the total waiting time is usually closer to 100 ms, not 200 ms (we’re simplifying, but that’s the idea).
This approach is very similar to examples in Kotlin materials that show starting multiple concurrent tasks with coroutines: same idea — many independent pieces of work start, and then we just wait until they finish.
6. Practical example: “loading a profile” in the console
So the examples aren’t “in a vacuum”, let’s put together a small scenario: a console program that “loads a user profile”. For real, we’re not hitting the network or a DB yet (those are separate topics), so we’ll simulate long operations with delay.
Imagine we need to get three things: name, balance, and notification count. From a business perspective, these are independent chunks, and we can do them concurrently.
Three suspend functions that “take a long time”
It’s important to write functions small and honest: if there’s a delay inside, the function should be suspend.
import kotlinx.coroutines.delay
suspend fun loadUserName(): String {
delay(120)
return "Alice"
}
suspend fun loadBalance(): Int {
delay(200)
return 150
}
suspend fun loadNotifications(): Int {
delay(80)
return 3
}
Even now you can notice something nice: the functions look like regular ones, “top to bottom”. And that’s one of the reasons Kotlin loves coroutines: async doesn’t turn the code into callback spaghetti.
Sequential version: simple and honest, but slower
First, let’s do it “as you’d write out of habit”: call the functions one after another. That’s not a mistake — sometimes that’s exactly what you need. But we want to see the difference.
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val name = loadUserName()
val balance = loadBalance()
val notifications = loadNotifications()
println("$name: $$balance, notifications=$notifications")
// Alice: $150, notifications=3
}
Meaning: we wait 120 ms, then another 200 ms, then another 80 ms. In total, the waiting time “adds up”.
Concurrent version: start everything at once and wait for results
Now the same logic, but with async. We start three computations, get three “promises”, and then extract the results via await().
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val nameD = async { loadUserName() }
val balanceD = async { loadBalance() }
val notifD = async { loadNotifications() }
println("${nameD.await()}: $${balanceD.await()}, notifications=${notifD.await()}")
// Alice: $150, notifications=3
}
The result is the same, but the “waiting time” should be closer to the longest chunk (in our case it’s loadBalance() at 200 ms), not the sum of all delays. And this is already closer to real life: often we’re waiting on network/disk, and concurrency gives the feeling that “the app responds faster”, even though it doesn’t magically speed up the CPU.
7. Where to use launch and where to use async
It’s very easy to slide into “I’ll wrap everything in async, because I can”. Usually that’s a bad idea: the code becomes less expressive. We want the intention to be visible in the code: “I’m starting an action” or “I’m starting a computation that returns a result”.
Below is a small table that helps you choose without reading tea leaves:
| Situation in code | What makes more sense | Why |
|---|---|---|
| You need to print a log / show a message / write something | |
No result is needed; the fact of the action matters |
| You need to get a value (number/string/list) | |
There is a result; it must be returned and used |
| You want to start 2–5 independent computations and then collect the results | |
It expresses “parallel waiting” well |
| You want to do background “parallel” printing/indicator (simplified) | |
It’s a side effect (output), not a computation |
Note: we are not discussing the nuances of lifecycle management yet (cancellation, Job, hierarchies). Today it’s important to learn how to choose the right start form for the task, without overcomplicating things.
Can you mix launch and async
In real programs, you often do both: in parallel you “print/log something” and in parallel you “compute/load something”. The main thing is not to turn the program into a fireworks show where everything blinks and nobody understands who is responsible for what.
Let’s make a small example: we concurrently start loading data (async) and print “start/finish” as separate actions (launch).
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
launch { println("Loading profile...") } // Loading profile...
val nameD = async { delay(100); "Alice" }
val notifD = async { delay(80); 3 }
println("Hi, ${nameD.await()}! You have ${notifD.await()} notifications.")
// Hi, Alice! You have 3 notifications.
}
Yes, here launch looks “unnecessary”, because you could have just done println directly. But as a learning example it shows the difference in intent: launch is “an action on its own”, async is “a result on its own”.
8. Minimal notes on exceptions in coroutines
When you write concurrent code, exceptions don’t go away. They just become more “unexpected” if you don’t understand where exactly you “receive” them.
With async, an important practical detail is this: if an error happens inside async { ... }, it often “shows up” at await() (because that’s exactly where you try to get the result).
I’ll show a short example: division by zero. Don’t try this at home… actually, do try it — and watch the behavior.
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val d = async { 10 / 0 }
println("Before await") // Before await
println(d.await()) // ArithmeticException here
}
We see that the program manages to print Before await, and then crashes on await(). That’s logical: the error was “in computing the result”, and await() is the point where you ask for the result to be exposed.
With launch, the story is also not simple, but today we won’t dive into exception-handling strategies in coroutine groups. Just keep one honest rule in mind: concurrency doesn’t remove the need to think about errors; it only changes where you notice them.
9. Common mistakes when working with launch and async/await
Mistake #1: using launch when you need a result.
Often a beginner starts launch { val x = ... }, and then tries to “somehow return x outside”. It looks like trying to carry water in a sieve: launch is designed to “do an action”, and that’s why it doesn’t give you a normal result contract of type T. If you need a value, choose async and retrieve the result via await().
Mistake #2: forgetting that Deferred<T> is not T.
Deferred is not a number and not a string; it’s a “promise”. When you print a Deferred, you’ll see internal information, not the result. If you then pass a Deferred somewhere that expects an Int, the compiler will (rightfully) complain. The fix is simple: be disciplined about calling await() exactly where you truly need the result.
Mistake #3: calling await() immediately after each async, and then being surprised there’s “no speedup”.
If you write async {...}.await() twice in a row, you’re effectively doing “start → wait”, “start → wait”. Concurrency is lost, and the total wait becomes similar to the sum of delays again. The correct pattern: start several async first, then wait.
Mistake #4: wrapping everything in coroutines for no reason.
Sometimes the fastest way to make a program slower and more confusing is to add concurrency “just in case”. If an operation is instantaneous (for example, val x = 1 + 2), async only complicates the code. Coroutines are especially useful where there is waiting or independent chunks of work.
Mistake #5: confusing a “coroutine” with a “thread” and expecting strict parallelism.
A coroutine is lightweight and can suspend; a thread is a heavyweight OS resource. Coroutines can run concurrently, and that is already useful. But nobody promised “mandatory parallelism” like “two coroutines = two CPU cores”.
GO TO FULL VERSION