Learn Kotlin Β· 15/18

Coroutines I: Asynchronous Programming Basics

6 min read

Welcome, future Kotlin Coroutine master! πŸ‘‹ Get ready to dive into the world of asynchronous programming. We'll make it fun and, most importantly, easy to understand. By the end of this guide, you'll be juggling tasks like a pro circus performer.


πŸ€” What are Coroutines? Lightweight Threads Explained

Let's start with a common problem. Imagine you're building an Android app. You need to fetch some data from the internet, say, a list of trending cat videos. 🐈 If you do this on the main thread (the one responsible for the user interface), your app will freeze until the data arrives. Nobody likes a frozen app, especially when there are cat videos at stake!

This is where asynchronous programming comes in. It's a way to perform long-running tasks in the background without blocking the main thread.

Now, you might be thinking, "What about traditional threads?" You're not wrong! Threads can do this, but they are heavyweight. Creating a lot of threads can consume a lot of memory and lead to performance issues. It's like sending a whole truck to deliver a single pizza. πŸššπŸ•

Enter Coroutines!

Coroutines are like very lightweight threads. You can launch thousands of them without breaking a sweat (or your app's memory). They are a more efficient and structured way to handle asynchronous tasks.

Think of it like this: A thread is like a full-time employee. You have to hire them, give them a desk, and they take up resources. A coroutine is like a freelance consultant. They come in, do a specific task, and then they're gone, using minimal resources.

Under the Hood: Coroutines are not threads. They are tasks that can be executed by a smaller, shared pool of threads. This is what makes them so lightweight and efficient. They are managed by the Kotlin runtime, which intelligently switches between them.


⏸️ Suspend Functions: Pausing and Resuming Execution

So, how do coroutines work their magic? Through the power of suspend functions!

A suspend function is a special kind of function that can be paused and resumed later. When a coroutine calls a suspend function, it doesn't block the thread. Instead, it "suspends" its own execution, freeing up the thread to do other work. Once the suspend function is done, the coroutine resumes where it left off.

It's like cooking. 🍳 Imagine you're making breakfast. You put the toast in the toaster and you don't just stand there staring at it for two minutes, right? You go and start making the coffee. When the toast is ready, the toaster pops, and you go back to buttering it. You've "suspended" your toast-making task to do something else.

Here's what a suspend function looks like in code:

kotlin
import kotlinx.coroutines.delay

suspend fun fetchCatVideos(): List<String> {
    // Simulate a network call
    delay(2000) // This is a suspend function!
    return listOf("Cat playing piano", "Kitten falling asleep", "Funny cat compilation")
}

The delay() function is a special suspend function provided by the coroutines library. It pauses the coroutine for a specified amount of time without blocking the thread.

Key takeaway: suspend functions are the building blocks of coroutines. They allow you to write asynchronous code that looks just like regular, sequential code. No more callback nightmares!


πŸš€ Coroutine Builders: launch, async, and runBlocking

Now that we know about suspend functions, how do we actually start a coroutine? We use coroutine builders. Think of them as the launchpads for our coroutine rockets. πŸš€

There are three main builders you'll use frequently:

1. launch

launch is a "fire and forget" coroutine builder. You use it when you want to start a coroutine that doesn't return a result. It's perfect for things like updating a database, sending a network request where you don't need the response right away, or any background task.

kotlin
import kotlinx.coroutines.*

fun main() {
    GlobalScope.launch { // Launch a new coroutine in the background
        delay(1000L)
        println("World!")
    }
    println("Hello,")
    Thread.sleep(2000L) // Block the main thread to keep the JVM alive
}

In this example, "Hello," is printed first, then after a 1-second delay, "World!" is printed by the coroutine.

2. async

async is used when you want to perform a task asynchronously and get a result back. It returns a Deferred object, which is like a promise for a future value. You can then call .await() on the Deferred object to get the result when it's ready.

kotlin
import kotlinx.coroutines.*

suspend fun getTheAnswer(): Int {
    delay(1000L)
    return 42
}

fun main() = runBlocking {
    val theAnswer: Deferred<Int> = async { getTheAnswer() }
    println("The answer is ${theAnswer.await()}")
}

Here, we start a coroutine with async to get "the answer". While it's being calculated, we could be doing other things. When we need the result, we call .await().

3. runBlocking

runBlocking is a bit different. It's a coroutine builder that blocks the current thread until the coroutine inside it is complete. It's mainly used for bridging the gap between the blocking world and the suspending world. You'll often see it in main functions in examples to prevent the program from exiting before the coroutines are finished.

Industry Practice: In real-world Android development, you'll rarely use runBlocking. It's mostly for educational purposes and testing. You'll primarily be using launch and async within specific CoroutineScopes tied to the lifecycle of your application components (like a ViewModel or an Activity). GlobalScope is also generally discouraged in application code because if a coroutine launched in GlobalScope gets stuck, it will never terminate, potentially causing a memory leak.


πŸ—ΊοΈ Dispatchers: Managing Threads (Main, IO, Default)

So, we have these lightweight coroutines, but which threads do they actually run on? That's where Dispatchers come in.

Dispatchers determine which thread or thread pool the coroutine will use for its execution. Think of them as the traffic controllers for your coroutines. 🚦

There are three main dispatchers you'll use:

  • Dispatchers.Main: This dispatcher is used for UI-related tasks. In Android, this is the main thread. You should always use this dispatcher when you need to update the UI.
  • Dispatchers.IO: This dispatcher is optimized for I/O-intensive tasks, like making network requests, reading from or writing to a database, or reading and writing files.
  • Dispatchers.Default: This is used for CPU-intensive work, like sorting a large list, parsing a large JSON file, or performing complex calculations.

You can specify the dispatcher when you launch a coroutine:

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch(Dispatchers.Main) {
        // Update UI
    }

    launch(Dispatchers.IO) {
        // Network request
    }

    launch(Dispatchers.Default) {
        // Heavy computation
    }
}

By using dispatchers, you can ensure that your tasks are running on the most appropriate thread, leading to a more responsive and efficient application.

Fun Fact: Before coroutines, managing threads for different types of tasks was a much more manual and error-prone process. Dispatchers simplify this immensely, making your asynchronous code cleaner and safer.


πŸ“œ Getting Started: Setup

To start using coroutines in your Kotlin project, you need to add the following dependency to your build.gradle.kts (or build.gradle) file:

For Gradle Kotlin DSL (build.gradle.kts):

kotlin
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}

For Groovy DSL (build.gradle):

groovy
dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3'
}

Always check for the latest version of the library.


πŸ“š Further Reading and References

Challenge

Challenge: Concurrent Data Fetching

Your task is to implement the fetchUserDataAndPosts function. This function should simulate fetching a user's profile data and their list of posts from two separate API endpoints concurrently.

Requirements:

  1. The function must be a suspend function as defined in the initial code.
  2. You must launch two coroutines that run in parallel to fetch the data. The first should call fetchUserFromApi and the second should call fetchPostsFromApi.
  3. Use the async coroutine builder for both tasks since you expect a result from each.
  4. Both asynchronous tasks must be explicitly configured to run on the Dispatchers.IO context, which is suitable for network operations.
  5. Wait for both concurrent tasks to complete and retrieve their results.
  6. Combine the results from both tasks into a Pair<UserData, List<Post>> and return it.

Expected result

Your implementation of fetchUserDataAndPosts should correctly use the async builder twice within a coroutineScope. Each async block must specify Dispatchers.IO as its context. The function should then call .await() on both Deferred objects returned by async to get the results. By running these tasks concurrently, the total execution time should be approximately that of the longest-running task (1500ms), not the sum of both (~2500ms). The final code should return a Pair containing the UserData object and the List<Post>.

kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.