retryIfWithExponentialBackoff

suspend fun <R> retryIfWithExponentialBackoff(retries: Long = 3, base: Duration = 200.milliseconds, factor: Double = 2.0, shouldRetry: (Throwable) -> Boolean, block: suspend () -> R): R(source)

Executes a suspend operation with retry using exponential backoff and jitter, but only for exceptions matching shouldRetry - combines retryWithExponentialBackoff's backoff strategy with retryIf's conditional retry, which neither function offers alone.

Return

The result of the successful execution

Parameters

retries

The maximum number of retry attempts after the initial attempt (defaults to 3)

base

The base duration for exponential backoff (defaults to 200 milliseconds)

factor

The exponential factor (defaults to 2.0)

shouldRetry

Predicate that receives the exception and returns true to retry

block

The suspend operation to execute

Type Parameters

R

The return type of the suspend operation

Throws

if shouldRetry returns false or all retries are exhausted

Example usage:

val response = retryIfWithExponentialBackoff(
retries = 5,
shouldRetry = { it is IOException || it is ServerErrorException },
) {
httpClient.get("/api/data")
}