Skip to content

Instantly share code, notes, and snippets.

@jlccaires
Created July 23, 2019 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlccaires/d4c06d800c057a6c042694164e292d64 to your computer and use it in GitHub Desktop.
Save jlccaires/d4c06d800c057a6c042694164e292d64 to your computer and use it in GitHub Desktop.
RxJava Auto retry with attempt limit
fun main() {
Observable.create<String> {
while (true) {
if (it.isDisposed) break
val input = readLine()
if (input == null || input == "e") {
it.onError(Exception())
continue
}
it.onNext(input)
}
}.retryWhen {
it.map { 1L }
.scan { a, b -> a + b }
.flatMap { errorCount ->
if (errorCount < 3) Observable.timer(errorCount, TimeUnit.SECONDS)
else Observable.error(Exception("No more retries"))
}
}
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.trampoline())
.blockingSubscribe(
{
println(it)
},
{
println("completed")
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment