Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
31: Introduction to Coroutines
Up until now, everything we've written has been synchronous. One line happens, then the next. That's fine for calculating a Fibonacci sequence, but the moment you hit a network request or a heavy database query, your entire application freezes. In the professional world, we call that "blocking the main thread," and it's the fastest way to get your app uninstalled.
Kotlin Coroutines solve this by allowing us to write asynchronous code that looks like synchronous code. I like to think of a coroutine as a "lightweight thread." You can spawn thousands of them without crashing your JVM, because they don't each map to a heavy OS thread; they can "suspend" their execution, freeing up the thread for other work, and then resume exactly where they left off.
Simulating a Slow Network Call
Let's build a simple user profile loader. Imagine we have a mock API that takes a second or two to return data. I'll start by defining a function that simulates this delay using delay(), which is a special suspending function provided by Kotlin.
suspend fun fetchUserAvatar(): String {
delay(1000L) // Simulate network latency
return "https://cdn.example.com/user123.jpg"
}
suspend fun fetchUserName(): String {
delay(1000L)
return "Jane Doe"
}
Notice that suspend keyword. This is the most important part of the syntax. It tells Kotlin: "This function might take a while, and it's allowed to pause the execution of the coroutine without blocking the underlying thread."
The "Suspend" Wall
Here is where I usually trip up when I'm first explaining this to juniors (and where I tripped up myself years ago). I tried to call these functions directly from my main function like this:
fun main() {
val name = fetchUserName()
println("User name is $name")
}
The compiler immediately yells at me: "Suspend function 'fetchUserName' should be called only from a coroutine or another suspend function."
This is a safety feature. Kotlin won't let you call a suspending function in a regular blocking context because that would defeat the whole purpose of coroutines. You need a "bridge" to enter the world of coroutines.
Creating a Coroutine Scope
To fix this, we need a CoroutineScope. In a real Android app, you'd use viewModelScope or lifecycleScope. But for a simple console app, I'll use runBlocking. It blocks the current thread until everything inside it is finished—perfect for a main function, but dangerous if used inside a UI thread.
import kotlinx.coroutines.*
fun main() = runBlocking {
println("Fetching profile...")
val name = fetchUserName()
val avatar = fetchUserAvatar()
println("Done! User: $name, Avatar: $avatar")
}
If you run this, it works. But there's a problem: it takes two seconds. Why? Because fetchUserName runs, waits a second, finishes, and then fetchUserAvatar starts. We are still acting synchronously, even though we're inside a coroutine.
Actually Doing Things in Parallel
To get that performance boost, I'll use the launch builder. launch is "fire and forget"—it starts a new coroutine in the background and immediately moves to the next line of code.
I'll wrap my calls in launch blocks to see how they behave:
fun main() = runBlocking {
println("Fetching profile...")
launch {
val name = fetchUserName()
println("Got name: $name")
}
launch {
val avatar = fetchUserAvatar()
println("Got avatar: $avatar")
}
println("Requests sent!")
}
Now, the output changes. "Requests sent!" prints almost immediately, and then a second later, both the name and avatar pop up. We've effectively cut our waiting time in half because both network simulations were running concurrently.
📋 Practical Task
Exercise: Building a Concurrent System Status Checker
You are building a monitoring tool that needs to check the status of three different services: a Database, a Cache server, and an External API. Each check takes a different amount of time to complete.
Requirements:
- Create three
suspendfunctions:checkDatabase(),checkCache(), andcheckApi(). - Each function should use
delay()to simulate work (e.g., 500ms, 1200ms, and 800ms respectively) and then return a string like "Database: Online". - In your
mainfunction, userunBlockingto create a scope. - Use
launchto trigger all three checks concurrently. - Print a message saying "Checking systems..." at the start, and ensure the program only finishes after all three checks have printed their results to the console.
There are no comments for now.