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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With