Skip to Content
Course content

102: Channels for Coroutine Communication

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

Think of a Channel like a conveyor belt in a sushi restaurant. You've got a chef (the producer) who makes a roll and places it on the belt. Then you've got a hungry customer (the consumer) who sits there and picks up whatever roll arrives in front of them.

The beauty of this system is that the chef doesn't need to know exactly who is eating the sushi or when they'll eat it; they just keep putting food on the belt. Similarly, the customer doesn't need to go into the kitchen and pester the chef; they just wait for the belt to bring the food to them. If the belt is full, the chef has to wait a second before adding more. If the belt is empty, the customer just waits patiently. This "waiting" is exactly what happens when a coroutine suspends.

Moving Data Instead of Sharing State

Up until now, you might have been tempted to use a shared mutable list or a thread-safe variable to move data between coroutines. Honestly? Don't. That's a recipe for race conditions and a lot of sleepless nights debugging weird crashes. In Kotlin, the mantra is: Do not communicate by sharing memory; instead, share memory by communicating.

Let's look at a real scenario. Imagine we're building a log analyzer. One coroutine is scanning a massive file for "ERROR" tags, and another coroutine is responsible for sending those errors to a remote monitoring server. We don't want the scanner to stop and wait for the network request to finish every single time it finds an error—that would be incredibly slow.

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun main() = runBlocking {
    // This is our "conveyor belt"
    val errorChannel = Channel<String>()

    // The Producer: Scanning the logs
    launch {
        val logs = listOf("INFO: System start", "ERROR: Database timeout", "INFO: User login", "ERROR: NullPointerException")
        for (log in logs) {
            if (log.startsWith("ERROR")) {
                println("Scanner: Found error, sending to channel...")
                errorChannel.send(log) // Suspends if the channel is full
            }
        }
        errorChannel.close() // Tell the consumer we're done
    }

    // The Consumer: Sending to server
    launch {
        for (error in errorChannel) { // Suspends if the channel is empty
            println("Server: Uploading error to cloud: $error")
            delay(1000) // Simulate a slow network call
        }
        println("Server: All errors processed.")
    }
}

Dealing with the "Full Belt" Problem

In the example above, I used a "Rendezvous" channel. That's the default. It has no buffer, meaning the sender suspends until the receiver is actually ready to take the item. It's like the chef holding the plate out and refusing to let go until the customer grabs it.

Sometimes, you want a buffer. Maybe the chef can put five plates on the belt before they have to stop. You do this by passing a capacity to the Channel constructor: Channel<String>(5). Now, the scanner can find five errors and dump them onto the belt immediately, even if the server coroutine is lagging behind. It smooths out the "burstiness" of your data flow.

Closing the Line

You noticed I called errorChannel.close(). This is crucial. If you don't close the channel, the for (error in errorChannel) loop in the consumer coroutine will wait forever, thinking more data might eventually arrive. Closing the channel sends a special "close token" that tells the receiver, "That's all for today, you can stop waiting now."

I've seen plenty of memory leaks in production code simply because someone forgot to close a channel in a long-running service. Be diligent about it.




📋 Practical Task

Build a Concurrent Image Processing Pipeline

You need to simulate a system that processes images. You will create two coroutines and one channel:

  • The Image Loader: This coroutine should "load" 10 images (represented as strings like "image1.jpg", "image2.jpg", etc.). It should send these strings into a channel. To make it realistic, add a small delay(100) between each load.
  • The Image Filter: This coroutine should receive the image names from the channel and "apply a filter" (simply print "Applying grayscale filter to [image name]"). To simulate heavy processing, add a delay(500) for each image.

Requirements:
1. Use a Buffered Channel with a capacity of 3 to prevent the loader from blocking immediately.
2. Ensure the loader closes the channel after all images are sent.
3. The filter should use a for loop to consume the channel until it is closed.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.