Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What will happen if every request has a retrofit instance?

I was thinking about a question recently.

If every request has a retrofit instance,What will happen?

The reason I want every request has a retrofit instance:

Every retrofit instance has an OkHttpClient instance,so I want add Interception to OkhttpClient,but not every request should be intercepted,and I also want to add some same headers to OkHttpClient,but not every request must has these same headers,like when it's login request,I don't need add token.,but other request may need.

So my way is to let every request has a retrofit instance,I have a demo before,but the quantity of requests are few,So I am not sure whether when there are too many requests will it come trouble?

I have 2 questions:

1. Will it make some exceptions?Or Will it make stack overflow?

2. If there is some better way to solve the question?

Have someone else has the same experience or have some ideas to question?

like image 797
ChengTao Avatar asked Aug 30 '25 17:08

ChengTao


1 Answers

You can use @Headers annotation to add static/dynamic header to Retrofit. Moreover, you shouldn't create separate OkHttp instance as stated in documentation:

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools.

If you want different configuration for each OkHttp just use client.newBuilder() (available from version 3.x):

You can customize a shared OkHttpClient instance with newBuilder(). This builds a client that shares the same connection pool, thread pools, and configuration. Use the builder methods to configure the derived client for a specific purpose.

If @Headers is not suitable for you, just create as many configurations of OkHttpClient as you want to create different Retrofit services and you will be ok.

http://square.github.io/okhttp/3.x/okhttp/

like image 110
Than Avatar answered Sep 02 '25 06:09

Than