Skip to content

Instantly share code, notes, and snippets.

@harryhan24
Forked from yongjhih/backoff.kt
Created April 11, 2019 19:31
Show Gist options
  • Save harryhan24/bb8a143adc795e44ae892f85661f9e1e to your computer and use it in GitHub Desktop.
Save harryhan24/bb8a143adc795e44ae892f85661f9e1e to your computer and use it in GitHub Desktop.
fun <T> backoff(times: Int = Int.MAX_VALUE, predicate: (Throwable, Int) -> Boolean = { _, _ -> true }): ObservableTransformer<T, T> {
return ObservableTransformer {
it.retryWhen { attempts ->
val counter = AtomicInteger()
attempts.takeWhile { e -> counter.getAndIncrement() < times && predicate(e, counter.get()) }
.flatMap { Observable.timer(counter.get().toLong(), TimeUnit.SECONDS) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment