Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask.onPostExecute()'s parameters vs instance variable

Working on my AsyncTask I wonder why I should use the onPostExecute()'s parameter, when I can just use a class level instance variable in my AsyncTask class to share data between doInBackground() and onPostExecute().

Both work, but are there any pro's and con's to each approach?

Edit: when I say 'instance variable', I'm talking about a private instance variable in the AsyncTask extended class. When the class dies, the instance variable dies too.

like image 616
Jop van Raaij Avatar asked Jan 24 '12 09:01

Jop van Raaij


2 Answers

Well, it may reduce the probability of memory leak, since you do not hold a reference to your object at class level, but only it those AsyncTask methods.

It will also eliminate the synchronization problems, as @nico_ekito mentioned

like image 84
a.ch. Avatar answered Nov 05 '22 12:11

a.ch.


I have found that using instance variables within the AsyncTask is not thread safe. In my case, if I caught and Exception in doInBackground(), I'd set it to my AsyncTask's Exception instance variable. Then I'd check if the variable was null or not in onPostExecute() (I don't cancel() because I may want to display a message in the exception to the user).

Anyway, from time to time I'd log that I caught an Exception in doInBackground, but in onPostExecute the instance variable would be null. The documentation does say that the methods are called synchronously, so I can't explain WHY that happens, but I saw it happen several times.

Finally, I changed my "Result" class to contain both an exception and the original result I wanted to pass to onPostExecute. That works just fine.

like image 35
Vito Andolini Avatar answered Nov 05 '22 12:11

Vito Andolini