Is Interceptor.Chain.proceed() a Thread Blocking Method?

Viewed 1063

Suppose I create my own implementation of an Interceptor from OkHttp3:

class MyInterceptor: Interceptor {

    private val gson = Gson()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // Will this block the main thread?
        val response = chain.proceed(request)

        return Response.Builder()
            .code(200)
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .message("OK")
            .body(
                gson.toJson("foo").toResponseBody("application/json".toMediaType())
            )
            .build()
    }
}

Will the call to chain.proceed() block the main thread? This seems counter-intuitive to what is provided Retrofit's support of suspend functions, which is built on top of OkHttp3. Because I've chosen to use an interceptor, do I now lose that async support?

1 Answers

Will the call to chain.proceed() block the main thread?

It will block whatever thread intercept() was called on. If that is the main application thread, you will have other problems (e.g., NetworkOnMainThreadException), and that situation is unrelated to whether or not you have this interceptor.

Because I've chosen to use an interceptor, do I now lose that async support?

No. This is all operating underneath that async support. If this OkHttp request was kicked off by a Retrofit suspend API, then intercept() should be called on a background thread (whichever one OkHttp/Retrofit is using from its thread pool).

Related