Last active
January 10, 2022 05:55
-
-
Save agustarc/b81c357d884c3e0bd60aefdc03ee461b to your computer and use it in GitHub Desktop.
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
internal typealias RETRY_PREDICATE = (Throwable) -> Boolean | |
internal const val MAX_RETRIES = 3L | |
internal const val DEFAULT_INTERVAL = 1L | |
internal val TIMEOUT: RETRY_PREDICATE = { it is SocketTimeoutException } | |
internal val NETWORK: RETRY_PREDICATE = { it is IOException } | |
internal val SERVICE_UNAVAILABLE: RETRY_PREDICATE = { it is HttpException && it.code() == 503 } | |
internal fun <T> applyRetryPolicy( | |
vararg predicates: RETRY_PREDICATE, | |
maxRetries: Long = MAX_RETRIES, | |
interval: Long = DEFAULT_INTERVAL, | |
unit: TimeUnit = TimeUnit.SECONDS, | |
resumeNext: (Throwable) -> SingleSource<T> | |
) = SingleTransformer<T, T> { single -> | |
single.retryWhen { attempts -> | |
Flowables.zip( | |
attempts.map { error -> if (predicates.count { it(error) } > 0) error else throw error }, | |
Flowable.interval(interval, unit) | |
).map { (error, retryCount) -> if (retryCount >= maxRetries) throw error } | |
}.onErrorResumeNext(resumeNext) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment