Careeroza
Channel Capacity
Buffer Types
| Capacity | send suspends when | Notes |
|---|---|---|
Channel.RENDEZVOUS (default, 0) | no receiver is waiting | sender and receiver meet |
Channel.BUFFERED (64) | buffer of 64 is full | good default for events |
Channel(n) | n items are waiting | fixed buffer |
Channel.UNLIMITED | never | can use unlimited memory |
Channel.CONFLATED | never | keeps only the latest value |
Example
Example
A buffer of 2 lets the producer run ahead by two items. A conflated channel keeps only the newest value.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val buffered = Channel<Int>(capacity = 2)
val producer = launch {
for (i in 1..4) {
buffered.send(i)
println("sent $i")
}
buffered.close()
}
delay(100) // nobody receives yet: producer stops after the buffer is full
println("--- consumer starts")
for (x in buffered) println("received $x")
producer.join()
val latest = Channel<String>(Channel.CONFLATED)
latest.send("location A")
latest.send("location B")
latest.send("location C")
println("conflated receive: ${latest.receive()}")
}Output
sent 1 sent 2 --- consumer starts received 1 received 2 received 3 sent 3 sent 4 received 4 conflated receive: location C