Skip to content

Instantly share code, notes, and snippets.

@ssoper
Last active December 29, 2021 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssoper/21eaf363a9c14d3ecbd4338ba7ce27b5 to your computer and use it in GitHub Desktop.
Save ssoper/21eaf363a9c14d3ecbd4338ba7ce27b5 to your computer and use it in GitHub Desktop.
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>()
.handle(ExpiredTokenError::class.java, InvalidTokenError::class.java)
.withDelay(Duration.ofSeconds(1))
.withMaxRetries(1)
.onRetry {
authorization.renewSession()?.let {
println("Re-authorization of session succeeded")
} ?: run {
println("Re-authorization of session failed, creating new session")
session = authorization.createSession()
}
}
.build()
val client = OkHttpClient.Builder()
.addInterceptor(HttpInterceptor(session.keys))
val retrofit = Retrofit.Builder()
.client(client.build())
.baseUrl("https://host/api/endpoint")
.build()
val call = retrofit.create(SomeApi::class.java) // 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 {
call.execute()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment