Channel Basics: send, receive, and close
Create channels, send and receive values, and close them properly.
What Is a Channel?
A Channel is a coroutine primitive for communicating between coroutines — like a blocking queue but suspending. Think of it as a pipe: one side sends, the other receives.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val channel = Channel<Int>()
launch {
for (i in 1..5) channel.send(i)
channel.close()
}
for (x in channel) println(x) // 1 2 3 4 5
}send and receive
send(value) suspends until the receiver is ready. receive() suspends until a value is available.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = Channel<String>()
launch {
ch.send("ping")
println("sent")
}
val msg = ch.receive()
println("received: $msg")
}All lessons in this course
- Channel Basics: send, receive, and close
- Channel Types: Rendezvous, Buffered, Conflated, Unlimited
- Mutex and Semaphore for Shared State
- Actors and Structured State Management