tryReceive

abstract fun tryReceive(): ChannelResult<E>(source)

Attempts to retrieve an element without waiting, removing it from the channel.

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)
    }
}