tryReceive
Attempts to retrieve an element without waiting, removing it from the channel.
When the channel is non-empty, a successful result is returned, and ChannelResult.getOrNull returns the retrieved element.
When the channel is empty, a failed result is returned.
When the channel is already closed for
receive
, returns the "channel is closed" result. If the channel was closed with a cause (for example, cancelled), ChannelResult.exceptionOrNull contains the cause.
This function is useful when implementing on-demand allocation of resources to be stored in the channel:
val resourcePool = Channel<Resource>(maxResources)
suspend fun withResource(block: (Resource) -> Unit) {
val result = resourcePool.tryReceive()
val resource = result.getOrNull()
?: tryCreateNewResource() // try to create a new resource
?: resourcePool.receive() // could not create: actually wait for the resource
try {
block(resource)
} finally {
resourcePool.trySend(resource)
}
}
Content copied to clipboard