Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. Channel

Channel

A Kotlin Channel is a communication channel for passing data between coroutines. The sender sends data with send(), and the receiver retrieves it with receive() or a for loop.

Syntax

import kotlinx.coroutines.channels.*

// Create a Channel
val channel = Channel<Type>()
val buffered = Channel<Type>(capacity = 10)  // With buffer

// Send
channel.send(value)      // Suspends if the buffer is full

// Receive
val value = channel.receive()   // Suspends until data arrives
channel.close()                 // Close the channel

// Receive all data with a for loop
for (v in channel) {
    println(v)
}

// produce coroutine builder
val ch = produce<Type> {
    send(value)
}

Functions

Function / PropertyDescription
Channel(capacity)Creates a channel. The default has no buffer (rendezvous).
channel.send(value)Sends a value. Suspends until space is available if the buffer is full.
channel.receive()Receives a value. Suspends until data arrives.
channel.close()Closes the channel. The receiver processes any remaining data before finishing.
channel.isClosedForSendChecks whether the channel is closed for sending.
produce { send() }Launches a coroutine with a send-only channel.

Sample Code

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun main() = runBlocking {
    // Basic send and receive
    val channel = Channel<Int>()

    // Sender coroutine
    launch {
        for (i in 1..5) {
            channel.send(i)
            println("Sent: $i")
        }
        channel.close()  // Close the channel after sending is complete.
    }

    // Receive until the channel is closed (for loop)
    for (value in channel) {
        println("Received: $value")
    }

    // Use the produce builder to create a send-only channel.
    val squares = produce {
        for (i in 1..4) {
            send(i * i)
        }
    }
    squares.consumeEach { println("Square: $it") }
    // Square: 1, 4, 9, 16

    println("Done")
}

Notes

A Channel acts as a "pipe" between coroutines. With no buffer (the default), data is transferred the moment both sender and receiver are ready (rendezvous). A buffered channel works like a queue — sending does not block until the buffer is full.

If you do not call close() on a channel, the receiver will wait indefinitely. The produce builder automatically closes the channel when its block completes, making it convenient for send-only use cases.

For launching coroutines, see launch / async. For asynchronous data streams, see Flow — Basics.

If you find any errors or copyright issues, please .