Channel
Creates a channel. See the Channel interface documentation for details.
This function is the most flexible way to create a channel. It allows specifying the channel's capacity, buffer overflow strategy, and an optional function to call to handle undelivered elements.
val allocatedResources = HashSet<Int>()
// An autocloseable resource that must be closed when it is no longer needed
class Resource(val id: Int): AutoCloseable {
init {
allocatedResources.add(id)
}
override fun close() {
allocatedResources.remove(id)
}
}
// A channel with a 15-element buffer that drops the oldest element on buffer overflow
// and closes the elements that were not delivered to the consumer
val channel = Channel<Resource>(
capacity = 15,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
onUndeliveredElement = { element -> element.close() }
)
// A sender's view of the channel
val sendChannel: SendChannel<Resource> = channel
repeat(100) {
sendChannel.send(Resource(it))
}
sendChannel.close()
// A receiver's view of the channel
val receiveChannel: ReceiveChannel<Resource> = channel
val receivedResources = receiveChannel.toList()
// Check that the last 15 sent resources were received
check(receivedResources.map { it.id } == (85 until 100).toList())
// Close the resources that were successfully received
receivedResources.forEach { it.close() }
// The dropped resources were closed by the channel itself
check(allocatedResources.isEmpty())
For a full explanation of every parameter and their interaction, see the Channel interface documentation.
Parameters
either a positive channel capacity or one of the constants defined in Channel.Factory. See the "Channel capacity" section in the Channel documentation.
configures an action on buffer overflow. See the "Buffer overflow" section in the Channel documentation.
a function that is called when element was sent but was not delivered to the consumer. See the "Undelivered elements" section in the Channel documentation.
Throws
when capacity< -2