Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Last active April 11, 2019 19:31
Show Gist options
  • Save yongjhih/75c7dfcdbef795ef41ef01687d29609c to your computer and use it in GitHub Desktop.
Save yongjhih/75c7dfcdbef795ef41ef01687d29609c 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