Skip to content

Instantly share code, notes, and snippets.

@agustarc
Last active January 10, 2022 05:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save agustarc/b81c357d884c3e0bd60aefdc03ee461b to your computer and use it in GitHub Desktop.
Save agustarc/b81c357d884c3e0bd60aefdc03ee461b to your computer and use it in GitHub Desktop.
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