Created
September 20, 2018 04:46
-
-
Save operando/472006dbbc2e228b6238a6c26fdf5f99 to your computer and use it in GitHub Desktop.
Setup timeout dynamically with retrofit https://github.com/square/retrofit/issues/2561
This file contains 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
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