okhttp application level OkHttpClient instance

10,638

Solution 1

Using single instance is not a problem instead it is a common practice. You can check a similar app from github which uses dagger to make OkHttpClient singleton and injects it other modules.

And you can see in this discussion JakeWharton is also suggesting this kind of usage.

But it is better if you use a Singleton Pattern for this purpose.

Solution 2

Apart from what @bhdrkn correctly suggests, to definitely confirm that a singleton instance of OkHttpClient is a correct way to go, an excerpt from documentation:

Source: https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html

OkHttpClients should be shared

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.

Refer to Javadoc (link above) to see correct ways of initializing OkHttpClient instance.

Share:
10,638

Related videos on Youtube

Mutinda Boniface
Author by

Mutinda Boniface

Software Engineer

Updated on June 04, 2022

Comments

  • Mutinda Boniface
    Mutinda Boniface almost 2 years

    I was wondering if there will be any performance bottleneck or issues if I create one instance of OkHttpClient to serve my "entire android application". I.e.In my Application class, I create a static public variable that will contain a instance of OkHttpClient and whenever I need to do an http request I basically build a request object then use the created okhttpclient instance to fire the request.

    Code to be like this

    public class MyApplication extends Application {
        public static OkHttpClient httpClient;
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            httpClient = new OkHttpClient();
        }
    
    }
    
    // Making request 1
    Request request1 = new Request.Builder().url(ENDPOINT).build();
    Response response = MyApplication.httpClient.newCall(request1).execute();
    
    // Making request 2
    Request request2 = new Request.Builder().url(ENDPOINT).build();
    Response response = MyApplication.httpClient.newCall(request2).execute();