Created
February 9, 2025 07:38
-
-
Save raghunandankavi2010/40d9728a9690f7497431722e57da3934 to your computer and use it in GitHub Desktop.
Retry with exponential back off using flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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