withPermit

suspend fun <T> CallBudget.withPermit(cost: Int, lane: Lane, maxWait: Duration, block: suspend (Permit) -> Result<T>): Result<T>(source)

Acquires a permit, runs block with it and completes the permit as spent (no signals) in a finally unless the block completed or released it. An exception the block throws propagates after the permit is completed; a refused or closed acquire is returned as the failure and block does not run.

Stable Core. Not inline: a public inline function would put its body in every caller; the cost of a call through here is one lambda.

Return

the block's result, or the acquire's failure.

Parameters

cost

the units to charge; at least 1.

lane

the lane to charge.

maxWait

the longest the call may wait for its slot.

block

the work; it decides complete(signals) or release() for the permit.

Throws

if cost is below 1 or maxWait is negative.

kotlinx.coroutines.CancellationException

if the caller is cancelled.