Created
December 8, 2020 20:51
-
-
Save nwellis/6a0f71098edd3f3cc4d98ec3f3972335 to your computer and use it in GitHub Desktop.
Interceptor that allows override timeout settings per call.
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
| const val CONNECT_TIMEOUT_MS = "CONNECT_TIMEOUT_MS" | |
| const val READ_TIMEOUT_MS = "READ_TIMEOUT_MS" | |
| const val WRITE_TIMEOUT_MS = "WRITE_TIMEOUT_MS" | |
| /** | |
| * Allows dynamic setting of timeout headers. | |
| * | |
| * Usage: | |
| * ``` | |
| * @Headers("$CONNECT_TIMEOUT:10000", "$READ_TIMEOUT:10000", "$WRITE_TIMEOUT:10000") | |
| * ``` | |
| * | |
| * Read timeout = How long to wait for an API response (most commonly used timeout) | |
| * Write timeout = How long to wait for the app to send the request | |
| * Connect timeout = How long to wait to establish a connection with the API (TCP handshake) | |
| * | |
| * @see <a href="https://github.com/square/retrofit/issues/2561#issuecomment-345641958">Related GitHub Issue</a> | |
| */ | |
| object TimeoutInterceptor : Interceptor { | |
| override fun intercept(chain: Interceptor.Chain): Response { | |
| val request: Request = chain.request() | |
| val connectTimeout: Int = request.header(CONNECT_TIMEOUT_MS) | |
| ?.takeIf { it.isNotBlank() }?.toIntOrNull() ?: chain.connectTimeoutMillis() | |
| val readTimeout: Int = request.header(READ_TIMEOUT_MS) | |
| ?.takeIf { it.isNotBlank() }?.toIntOrNull() ?: chain.readTimeoutMillis() | |
| val writeTimeout: Int = request.header(WRITE_TIMEOUT_MS) | |
| ?.takeIf { it.isNotBlank() }?.toIntOrNull() ?: chain.writeTimeoutMillis() | |
| val builder: Request.Builder = request.newBuilder() | |
| .removeHeader(CONNECT_TIMEOUT_MS) | |
| .removeHeader(READ_TIMEOUT_MS) | |
| .removeHeader(WRITE_TIMEOUT_MS) | |
| 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