What are the different types of channels in Kotlin coroutines?
What are channels?
Channels provide a way to send or receive a stream of values. When we want to communicate between coroutines, we use channels. Channel itself is an interface that implements two other interfaces:
SendChannel: We use this when we want to send elements to the channel or when we want to close the channel.ReceiveChannel: We use this when we want to receive elements.
Types of channels
There are four channels we can use, but that typically depends on which capacity size of the channel we set. The following are the types of channels:
- Unlimited channel
- Rendezvous channel
- Conflated channel
- Buffered channel
Unlimited channel
This channel type has an unlimited capacity buffer. As it has unlimited capacity, the channel ought to acknowledge every one of the elements and afterward let them be received one after the other. To create a channel with unlimited capacity, use the following syntax:
Syntax
val channel = produce(capacity = Channel.UNLIMITED)
Rendezvous channel
This channel type has a capacity of 0. In this, the producer will always have to wait for the receiver. The exchange occurs only when the sender meets the receiver. To create a channel with rendezvous capacity, use the following syntax:
Syntax
val channel = produce(capacity = Channel.RENDEZVOUS)
Conflated channel
This channel type has a capacity as conflated and has a buffer of size 1. This means that the previous values will replace all the new values. To create a channel with conflated capacity, use the following syntax:
Syntax
val channel = produce(capacity = Channel. CONFLATED)
Buffered channel
This change has a fixed capacity size which by default is 64, and when the buffer is complete, the producer starts waiting for the receiver. To create a channel with buffered capacity, use the following syntax:
Syntax
val channel = produce(capacity = 3)// 3 or any number we want
cp App.kt /usr/kotlinx-coroutines/app/src/main/kotlin/kotlinx/coroutines/app && cd .. && cd /usr/kotlinx-coroutines/app && gradle run --build-cache
Explanation
- Line 1: Wrap a suspending main body using
coroutineScope. - Line 2: Create a channel using the
producefunction. This helps us to close the channel whenever the builder coroutine ends. Otherwise, we have to close the channel ourselves. The type we selected is of capacityChannel.UNLIMITED.
Note: If we want to use any other channel type, we must replace
Channel.UNLIMITEDwith our desired channel type.
- Line 4: Send the value to the channel. (We have set the loop to 10 here, so it will return us the indices multiplied by two up to the iterator).
- Line 11–12: Print all the channel values.
Free Resources