retryWithBackoff

suspend fun <T> retryWithBackoff(times: Int, initialDelay: Duration, factor: Double = 2.0, maxDelay: Duration = Duration.INFINITE, retryIf: (Throwable) -> Boolean = { true }, block: suspend (attempt: Int) -> T): T

Runs block up to times attempts with exponentially growing delays between failures.

The attempt number passed to block starts at 1. The first pause is initialDelay; every following pause is the previous one multiplied by factor and capped at maxDelay. A failure that retryIf rejects, and the failure of the final attempt, are rethrown unchanged.

Cancellation: a CancellationException thrown by block or while delaying is rethrown immediately, never retried, and never passed to retryIf.

Parameters

times

the maximum number of attempts, at least 1.

initialDelay

the pause after the first failed attempt.

factor

the multiplier applied to the pause after each failed attempt.

maxDelay

the upper bound for any pause.

retryIf

returns true when the given failure should be retried.

Throws

if times is less than 1, initialDelay or maxDelay is negative, or factor is not a positive finite number.