Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

okhttp application level OkHttpClient instance

Tags:

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(); 
like image 656
Mutinda Boniface Avatar asked Jun 17 '15 09:06

Mutinda Boniface


People also ask

Should OkHttpClient be Singleton?

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.

What is OkHttpClient?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

What is the difference between retrofit and OkHttp?

OkHttp is a pure HTTP/SPDY client responsible for any low-level network operations, caching, requests and responses manipulation. In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.


1 Answers

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.

like image 143
bhdrkn Avatar answered Oct 12 '22 23:10

bhdrkn