3

Our app needs to hit some REST services for data (less than 500KB mostly). I was analyzing what should be the best approach for handling the api calls. Possible options were:

  1. AsyncTask (seemingly the right candidate as per the Google docs.)
  2. Thread (regular java threads)

All we have inside an AsyncTask is the doInBackground() method that does the network call and the onPostExecute() that posts the result to a handler class (a java class; not android.os.Handler). The handler posts the result via EventBus to the calling Activity/Fragment.

The only advantage over a traditional Thread that I see by using the AsyncTask here is that the result is posted on the UI Thread. I read that AsyncTask pose the risk of a potential memory leak if the activity is destroyed as described in many threads in SO.

To avoid this, we are thinking of spawning regular Threads for the network access and use EventBus library to post the result directly to the UI thread in the Activity/Fragment. This gets rid of the Handler class to post the result and also the code looks cleaner.

My questions are:

  1. Is AsyncTask still the recommended approach inspite of the extra lines of code and the handler classes?
  2. Does the use of a regular Thread instead of an AsyncTask come with some risks that we have missed? We are only starting the Thread but not handling its lifecycle.
  3. Is the use of EventBus for our purposes correct?

Thanks in advance for your help.

Ashok
  • 435
  • 1
  • 4
  • 16

0 Answers0