Kotlin Coroutines in Android — 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.

Interface Channel implements both SendChannel and ReceiveChannel . Here I list down the commonly used functions:

public interface Channel<E> : SendChannel<E>, ReceiveChannel<E> {} public interface SendChannel<in E> {

public val isClosedForSend: Boolean

public val isFull: Boolean

public suspend fun send(element: E)

public fun offer(element: E): Boolean

public fun close(cause: Throwable? = null): Boolean

public fun invokeOnClose(handler: (cause: Throwable?) -> Unit)

} public interface ReceiveChannel<out E> {

public val isClosedForReceive: Boolean

public val isEmpty: Boolean

public suspend fun receive(): E

public fun poll(): E?

public fun cancel(cause: CancellationException? = null)

}

There are two important suspending functions — Channel.send() and Channel.receive(). The function name is very readable, one coroutine could use Channel.send() to send some values to a channel, and the other one could use Channel.receive() to get the values from the channel.

We may think of channel in the middle like a typical Queue , it orders element in a first-in-first-out manner. Let’s have a simple example here:

We send Integer 1~5 to the channel in Coroutine#1 and receive them in Coroutine#2. The values will be printed out sequentially:
['Evan Fang']
['Android', 'Programming', 'Channel', 'Kotlin Coroutines', 'Kotlin']