⚙️ Kotlin Coroutines Cheat Sheet (For Android Devs)
I like to share content that I use during study and work.
This is a cheatsheet that I used when developing with coroutines.
Coroutines are lightweight threads used for asynchronous and concurrent programming in Kotlin.
They allow you to run tasks like network or DB operations without blocking the main thread.
🔹 Core Keywords & Builders
Keyword / Builder | Description |
---|---|
suspend |
Marks a function that can be paused and resumed later |
launch |
Starts a coroutine that doesn’t return a result |
async |
Starts a coroutine that returns a Deferred result |
await() |
Waits for the result of an async coroutine |
withContext() |
Switches the coroutine context (e.g., Main, IO) |
runBlocking |
Starts a blocking coroutine (usually for testing) |
coroutineScope |
Creates a new scope that waits for all its children |
supervisorScope |
Similar to coroutineScope but failures don’t cancel siblings |
delay() |
Non-blocking sleep function |
yield() |
Yields execution to other coroutines temporarily |
🔹 Dispatchers
Dispatcher | Used for |
---|---|
Dispatchers.Main |
UI operations (Android main thread) |
Dispatchers.IO |
I/O tasks: networking, DB, file access |
Dispatchers.Default |
CPU-intensive work |
Dispatchers.Unconfined |
Executes in current thread (advanced use) |
🔹 Example 1: Basic Launch
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000)
println("World!")
}
println("Hello,")
}
Output:
Hello,
World!
🔹 Example 2: async/await
import kotlinx.coroutines.*
suspend fun fetchUser(): String {
delay(1000)
return "Bruno"
}
suspend fun fetchPosts(): List<String> {
delay(1000)
return listOf("Post 1", "Post 2")
}
fun main() = runBlocking {
val user = async { fetchUser() }
val posts = async { fetchPosts() }
println("User: ${user.await()}, Posts: ${posts.await()}")
}
Output:
User: Bruno, Posts: [Post 1, Post 2]
🔹 Example 3: withContext
import kotlinx.coroutines.*
suspend fun loadUserData() = withContext(Dispatchers.IO) {
// background work
"User data loaded"
}
fun main() = runBlocking {
val result = loadUserData()
println(result)
}
Output:
User data loaded
🔹 Flow basics
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun numbersFlow(): Flow<Int> = flow {
for (i in 1..3) {
emit(i)
delay(100)
}
}
fun main() = runBlocking {
numbersFlow()
.map { it * 2 }
.collect { println(it) }
}
Output:
2
4
6
You can try these examples yourself on Kotlin Playground.
Top comments (0)