Created
July 23, 2019 21:33
-
-
Save jlccaires/d4c06d800c057a6c042694164e292d64 to your computer and use it in GitHub Desktop.
RxJava Auto retry with attempt limit
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
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