Skip to Content
Course content

31: Introduction to Coroutines

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 suspend functions: checkDatabase(), checkCache(), and checkApi().
  • 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 main function, use runBlocking to create a scope.
  • Use launch to 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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.