Last active
December 9, 2019 08:27
-
-
Save mvasilova/16a8405044d642775376f2d18b9a88b2 to your computer and use it in GitHub Desktop.
Retry Flowable method on Error (RxJava 2) - Android (Kotlin)
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
//Class | |
import io.reactivex.Flowable | |
import io.reactivex.functions.Function | |
import java.util.concurrent.TimeUnit | |
class RetryWithDelay(private val maxRetries: Int, private val retryDelayMillis: Int, private val retryIf: Function<Throwable, Boolean>, private val unit: TimeUnit = TimeUnit.MILLISECONDS) : Function<Flowable<out Throwable>, Flowable<*>> { | |
private var retryCount: Int = 0 | |
override fun apply(attempts: Flowable<out Throwable>): Flowable<*> { | |
return attempts.doOnNext { println("RetryWithDelay $it") }.flatMap { throwable -> | |
if (retryIf.apply(throwable) && (maxRetries < 0 || ++retryCount < maxRetries)) { | |
// When this Flowable calls onNext, the original Flowable will be retried (i.e. re-subscribed). | |
Flowable.timer(retryDelayMillis.toLong(), unit) | |
} else Flowable.error<Any>(throwable) // Max retries hit. Just pass the error along. | |
} | |
} | |
} | |
//Extensions | |
import io.reactivex.Flowable | |
import io.reactivex.android.schedulers.AndroidSchedulers | |
import io.reactivex.exceptions.CompositeException | |
import io.reactivex.functions.Function | |
import io.reactivex.schedulers.Schedulers | |
fun <T> Flowable<T>.retryOnError(): Flowable<T> = this | |
.subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()) | |
.onErrorResumeNext { throwable: Throwable -> if (throwable is CompositeException) Flowable.error(throwable.exceptions[0]) else Flowable.error(throwable) } | |
.retryWhen(RetryWithDelay(3, 1000, Function { t -> t is ConnectException })) | |
//Usages | |
repository.getSomething() | |
.retryOnError() | |
.subscribe({ | |
// | |
}, { error -> | |
// | |
}).add() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment