Skip to content

Instantly share code, notes, and snippets.

@operando
Created September 20, 2018 04:46
Show Gist options
  • Save operando/472006dbbc2e228b6238a6c26fdf5f99 to your computer and use it in GitHub Desktop.
Save operando/472006dbbc2e228b6238a6c26fdf5f99 to your computer and use it in GitHub Desktop.
Setup timeout dynamically with retrofit https://github.com/square/retrofit/issues/2561
class TimeoutInterceptor : Interceptor {
companion object {
const val CONNECT_TIMEOUT = "CONNECT_TIMEOUT"
const val READ_TIMEOUT = "READ_TIMEOUT"
const val WRITE_TIMEOUT = "WRITE_TIMEOUT"
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val builder = request.newBuilder()
var connectTimeout = chain.connectTimeoutMillis()
var readTimeout = chain.readTimeoutMillis()
var writeTimeout = chain.writeTimeoutMillis()
val connectNew = request.header(CONNECT_TIMEOUT)
val readNew = request.header(READ_TIMEOUT)
val writeNew = request.header(WRITE_TIMEOUT)
if (!TextUtils.isEmpty(connectNew)) {
connectTimeout = Integer.valueOf(connectNew)
builder.removeHeader(CONNECT_TIMEOUT)
}
if (!TextUtils.isEmpty(readNew)) {
readTimeout = Integer.valueOf(readNew)
builder.removeHeader(READ_TIMEOUT)
}
if (!TextUtils.isEmpty(writeNew)) {
writeTimeout = Integer.valueOf(writeNew)
builder.removeHeader(WRITE_TIMEOUT)
}
return chain
.withConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
.withReadTimeout(readTimeout, TimeUnit.MILLISECONDS)
.withWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS)
.proceed(builder.build())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment