Kotlin Coroutines in Android — Channel

The simplest way to realize what’s Channel and how to use it.

Evan Fang
The Startup

--

I’ve introduced the Kotlin Coroutines basics and Suspending functions in the previous posts. Today, we’re going to learn something about Channel.

As we’ve learned in the Kotlin Coroutines in Android — Basics, Deferred transfers a single value between coroutines. Channel could be considered to provide a stream of values between coroutines.

Table of Contents

  1. Channel basics
  2. Channel.send() and Channel.receive()
  3. Channel.offer() and Channel.poll()
  4. SendChannel.close()
  5. ReceiveChannel.cancel(cause: CancellationException? = null)
  6. Channel capacity policy
    (1) Rendezvous channel
    (2) Buffered channel
    (3) Unlimited channel
    (4) Conflated channel

1. Channel basics

According to the official docs, we could know Channel is very similar to BlockingQueue. The biggest differences are that Channel will suspend coroutine instead of blocking it, and Channel can be closed when no more elements need to be added. We can send elements to the channel from the producer and receive them from the consumer.

--

--

Evan Fang
The Startup

An Android/Flutter engineer at LINE Corporation.