Kotlin Coroutines in Android — Channel
The simplest way to realize what’s Channel and how to use it.
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
- Channel basics
- Channel.send() and Channel.receive()
- Channel.offer() and Channel.poll()
- SendChannel.close()
- ReceiveChannel.cancel(cause: CancellationException? = null)
- 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.