Skip to content

Instantly share code, notes, and snippets.

Last active Dec 29, 2021
What would you like to do?
Use Failsafe to clone an OkHttp/Retrofit call in Kotlin on the 2nd attempt
// Assumes a long running process where the session keys need to be renewed or possibly even re-created
var session: Session = authorization.renewSession() ?: authorization.createSession()
val retryPolicy = RetryPolicy.builder<Any>()
.onRetry {
authorization.renewSession()?.let {
println("Re-authorization of session succeeded")
} ?: run {
println("Re-authorization of session failed, creating new session")
session = authorization.createSession()
val client = OkHttpClient.Builder()
val retrofit = Retrofit.Builder()
val call = retrofit.create( // Returns value of type Call<T>
val response = Failsafe.with(retryPolicy).get { x: ExecutionContext<Response<T>> ->
println("Attempts ${x.attemptCount}")
if (x.attemptCount > 0) {
call.clone().execute() // Can’t re-use original call on retry so need to clone it
} else {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment