Skip to content

Instantly share code, notes, and snippets.

@raghunandankavi2010
Created February 9, 2025 07:38
Show Gist options
  • Save raghunandankavi2010/40d9728a9690f7497431722e57da3934 to your computer and use it in GitHub Desktop.
Save raghunandankavi2010/40d9728a9690f7497431722e57da3934 to your computer and use it in GitHub Desktop.
Retry with exponential back off using flow
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.io.IOException
import kotlin.math.pow
fun <T> Flow<T>.retryWithExponentialBackoff(
times: Int,
initialDelay: Long,
factor: Double
): Flow<T> =
retryWhen { cause, attempt ->
if (cause is IOException && attempt < times) {
val delayTime = (initialDelay * factor.pow(attempt.toDouble())).toLong()
println("Retrying in ${delayTime}ms due to: ${cause.message}")
delay(delayTime)
true
} else {
false
}
}
fun main() = runBlocking<Unit> {
val retryTimes = 3
val initialDelay = 1000L // 1 second
val factor = 2.0
getRandomNumberFlow()
.retryWithExponentialBackoff(retryTimes, initialDelay, factor)
.catch { e -> println("Failed after $retryTimes retries due to: ${e.message}") }
.collect { value -> println("Collected value: $value") }
}
fun getRandomNumberFlow(): Flow<Int> = flow {
emit((1..10).random())
throw IOException("IO error occurred!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment