Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Multiple Interceptors to an OkHttpClient

I am trying to understand and use interceptors in an app. I am using the LoggingInterceptor and also including another interceptor for adding an authorization header. I noticed that in adding multiple interceptors, I need to call chain.proceed(chain.request) which basically runs the request multiple times and produce responses in all the interceptors I have added.

This is where I am quite confused, I don't want the request to run multiple times due to the number of interceptors I have. Is there any way I can achieve this?

like image 897
idrisadetunmbi Avatar asked Nov 06 '18 09:11

idrisadetunmbi


1 Answers

I'm not sure what you're seeing to conclude that you're running the request multiple times, but I can assure you that that's not the case.

OkHttp interceptors work as a chain, hence the name chain for the class you receive in the interceptor method. The interceptors are run in order of addition for requests and in reverse-order of addition for responses. For example, if you add first the logging interceptor and then the authentication one, you'll be running first the logging one for requests and then the authentication one. This means you won't see the authentication headers of the request (or any other authentication field for that matter) logged because they're added after you've logged the request.

By contrast, if you add the logging interceptor at the end, you'll see everything that was added by the previous interceptors.

Let's look at a generic example: A->B->C is a chain of interceptors that was added in alphabetical order. This means that A runs first, then B and then C for requests and for responses C runs first, then B and then A. When A is done with the request, it can call chain.proceed and it'll proceed with the request to B. The same for B when it wants to "proceed" the request in the chain. Once all interceptors are done, OkHttp will execute the request once and run the response through all the interceptors in reverse order. In other words, this is where the concept of chain comes in. It's almost like function composition in functional programming.

In the end, you're not running the request multiple times if you call chain.proceed(chain.request), you're simply passing it along the chain and waiting for the response.

Here's the official explanation which will be much better than mine.

like image 180
Fred Avatar answered Sep 22 '22 13:09

Fred