Skip to content

Channel Types

Devrath edited this page Dec 23, 2023 · 15 revisions

Types of Channels

  • Buffered
  • Conflated
  • Rendezvous
  • Unlimited

Channel Type --> Buffered

Observation

  • You can observe that we have given the capacity = 2 for the produce operator.
  • So elements sent are a max of 2 elements.
  • In the receive you can observe once the earlier 2 elements are received. Then one element is received as the one element is sent by the producer, So until then the second coroutine is suspended.
  • Only when one element is received is that space available for the channel buffer to send the data.

code

    private var receiveBufferChannel : ReceiveChannel<Countries> = Channel()

    fun usingBuffered() {
        // Co-Routine - 1
        viewModelScope.launch {

            // We are limiting the buffer capacity to 2
            receiveBufferChannel = produce(capacity = 2) {
                    println("Send Action : ----> USA")
                    send(Countries.USA)
                    println("Send Action : ----> Russia")
                    send(Countries.Russia)
                    println("Send Action : ----> India")
                    send(Countries.India)
                    println("Send Action : ----> France")
                    send(Countries.France)
                    println("Send Action : ----> Spain")
                    send(Countries.Spain)
                    println("Send Action : ----> Germany")
                    send(Countries.Germany)
                    println("Send Action : ----> Italy")
                    send(Countries.Italy)
            }

        }

        // Co-Routine - 2
        viewModelScope.launch {
            receiveBufferChannel.consumeEach { countries ->
                println("Receive Action : ----> $countries")
                println("---------------------------------")
                delay(3000)
            }
        }
    }

    enum class Countries { USA , Russia , India , France , Spain , Germany , Italy }

out-put

Send Action : ----> USA
Send Action : ----> Russia
Send Action : ----> India
Receive Action : ----> USA
---------------------------------
Send Action : ----> France
Send Action : ----> Spain
Receive Action : ----> Russia
---------------------------------
Send Action : ----> Germany
Receive Action : ----> India
---------------------------------
Send Action : ----> Italy
Receive Action : ----> France
---------------------------------
Receive Action : ----> Spain
---------------------------------
Receive Action : ----> Germany
---------------------------------
Receive Action : ----> Italy
---------------------------------

Channel Type --> Conflated

Observation

code

out-put

Clone this wiki locally