Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use one HttpClient per application?

I am looking for an efficient way to use the HttpClient for my android application. I use HttpClients inside different activities and I want use just one client for the application and pass it around the activities. Even though I look through some answers I couldn't figure out a way to use just one client for my several activities.

Can you please explain me how to implement this pattern possibly with a sample code?

Thank you.

like image 479
C.d. Avatar asked Oct 09 '22 02:10

C.d.


1 Answers

Here are a few things that you need to keep in mind before implementing such a HttpClient.

  1. A single instance of the client can be achieved by using a Singleton Pattern.
  2. Make sure you are using a Thread to do all your downloading in the background and dont use the UI Thread.
  3. Maintain a queue for all the download requests. A single Activity could have multiple requests to download various components such as, data, images, etc before it can be populated. All these requests need to be queued and run one after the other.
  4. Incase you switch an Activity before the HttpClient queue is clear, the queue should be cleared so that it does not stall the loading of your components of the new activity.

Hope it helps.

like image 181
Shubhayu Avatar answered Oct 13 '22 11:10

Shubhayu