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
102: Channels for Coroutine Communication
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.
There are no comments for now.