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.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:
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:
val channel = produce(capacity = Channel.UNLIMITED)
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:
val channel = produce(capacity = Channel.RENDEZVOUS)
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:
val channel = produce(capacity = Channel. CONFLATED)
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:
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
coroutineScope
.produce
function. 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 capacity Channel.UNLIMITED
.Note: If we want to use any other channel type, we must replace
Channel.UNLIMITED
with our desired channel type.
Free Resources