Producer-consumer
- Kotlin course
- Advanced
- Lesson 69/83
- 5 min
Learn the producer-consumer pattern with Channel.
Producer-consumer with Channel
Channel transfers data between coroutines. A producer writes with send, a consumer reads with receive or a for loop. This is the foundation of the producer-consumer pattern.
Example: val ch = Channel<Int>(3); ch.send(1); ch.close(). On the consumer side, for (v in ch) println(v). Channel(3) provides a 3-element buffer; close ends the stream. This pattern is used for parallel production and consumption.
Buffered vs rendezvous channel
Channel() defaults to rendezvous; send waits until a meeting. Channel(n) gives an n-element buffer; send waits when the buffer is full.
Example: Channel<Int>() is rendezvous, Channel<Int>(3) is buffered with 3. A buffered channel lets the producer work independently of the consumer. close() closes the channel; the consumer loop ends.
Practice Produce three values with Channel
Open main with runBlocking. Create val ch = Channel<Int>(3); send 1, 2, 3; call close(). Print the values with for (v in ch) println(v).
Starter code
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
// open main with runBlocking
// create a three-buffer channel, send three values, close, print with forSample solution
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val ch = Channel<Int>(3)
ch.send(1)
ch.send(2)
ch.send(3)
ch.close()
for (v in ch) println(v)
}Expected output
1 2 3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Channel parts
| Term | Meaning |
|---|---|
Channel<Int>(3) |
Buffered channel |
send(1) |
Production |
close() |
Stream end |
for (v in ch) |
Consumption |
2 Which method closes a Channel and ends the stream?
- stop()
- terminate()
- end()
- close() Correct answer
Explanation: close() closes the channel and ends consumption.
3 Complete the Channel definition
val ch = ____<Int>(3)
val ch = Channel<Int>(3)
Explanation: Channel<Int>(3) declares a 3-buffered channel.