CodeBlanks Logo Icon CodeBlanks

Channel

Learn inter-coroutine communication with Channel.

What is a Channel?

A Channel is a concurrent queue for passing data between coroutines. One coroutine puts a value with send, another reads it with receive.

It is created with Channel<T>(). send and receive are suspending functions; send waits if the buffer is full, receive waits if empty. This balances producer and consumer speeds. When a channel is closed (.close()), the consumer reads the last value and learns it is done.

send and receive

The producer coroutine puts a value with channel.send(value). The consumer reads one with channel.receive(). Both are suspending; they wait automatically when needed.

When the channel is closed, receive can no longer find a value and throws ClosedReceiveChannelException. Using for (value in channel) instead ends the loop cleanly when the channel closes. This reduces blocking risk.

Practice Send and receive with a Channel

Define val channel = Channel<Int>(). In a launch, call channel.send(10) and channel.send(20), then channel.close(). In the main flow, loop for (value in channel) and print each value with println("Got: $value").

Starter code

Main.kt
// Channel send and receive
// write here
fun main() = runBlocking {
    
}

Sample solution

Main.kt
fun main() = runBlocking {
    val channel = Channel<Int>()
    launch {
        channel.send(10)
        channel.send(20)
        channel.close()
    }
    for (value in channel) {
        println("Got: $value")
    }
}

Expected output

Got: 10
Got: 20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a Channel provide?

  • Data between coroutines Correct answer
  • Dispatcher choice
  • UI thread handling
  • Memory cache

Explanation: A Channel passes data between coroutines.

2 Complete the Channel type parameter

Question
val channel = Channel<____>()
Answer
val channel = Channel<Int>()

Explanation: A Channel takes a type parameter.

3 Match Channel parts

Term Meaning
Channel<T> Queue
send Puts a value
receive Takes a value
close Closes

All lessons in Advanced