Last active
December 29, 2021 21:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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