Skip to content

Instantly share code, notes, and snippets.

@ssoper
Last active Dec 29, 2021
Embed
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>()
.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