Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.