Coroutines
suspend functions, async/await, lightweight concurrency, channels and timeouts.
Coroutines are Kotlin's way to write asynchronous code that reads like ordinary sequential code. A suspend function can pause (for a network reply, a timer, a sensor) without blocking its thread, so thousands of coroutines can share a few threads. On Android they keep the UI responsive; on servers they handle many requests efficiently.
Coroutines in action
runBlocking starts a coroutine scope and waits for everything inside it (used in main and tests).
delay suspends without blocking the thread.
Two sequential calls of 100 ms take about 200 ms; with async they run concurrently.
10,000 coroutines each waiting 10 ms run easily — 10,000 threads would not.
A Channel passes values from one coroutine to another; closing it ends the receiving for loop.
withTimeoutOrNull cancels the slow call after 50 ms and returns null.
Structured concurrency
Thread.sleep(1000) // inside a coroutine Thread.sleep blocks the whole thread, stalling every other coroutine scheduled on it; delay suspends only this coroutine.
What is the difference between launch and async?
launch starts a coroutine for its side effects and returns a Job; async starts one that produces a value and returns a Deferred, whose result you get with await().