Sign in

How I got rid of all my AsyncTasks at once

Most of Android developers already know that AsyncTask became deprecated recently. So we have to refactor (usually) rather sensitive parts of our applications.

In general I was satisfied with AsyncTasks. But according to Google it was designed for different usage than how developers used it finally. Causing memory leaks, crashes…

So, we have several (frankly too many) alternative options to move forward:

  • Plain Threads on your own
  • Runnables passed to an Executor
  • Services
  • RxJava with or without Retrofit (instead of AsyncTasks used for network operations)
  • JobScheduler or WorkManager (for rare tasks)
  • Kotlin Coroutines
  • etc.

I’ve chosen coroutines. But instead of rewriting all my AsyncTasks individually I’ve implemented my own SupportAsyncTask (remembering the former support library) that invisibly uses coroutine inside but works along the same lifecycle and performs the same callbacks than the original AsyncTask did.

This way it was enough to simply change the base class of my AsyncTasks. And now execute() can be called directly.

Ok, I haven’t re-implemented the full AsyncTask behaviour just the “minimal” part I actually used… and what may be enough for you as well:

  • execute(), cancel(), isCancelled() implementations,
  • asynchronous call of doInBackground() (without implementation),
  • publishProgress() implementation to dispatch UI update to UI/Main thread,
  • onProgressUpdate(), onCancelled(), onPostExecute() callbacks on UI/Main thread (with default implementations)

That’s all.

Here and now I would like to give you as simple to understand example as possible but mainly the following Kotlin code has been working fine for 3 months in one of my apps with 5K+ daily users. I hope it will be useful for someone else too. (Please feel free to make logging more detailed, add onPreExecute() callback, etc.)

Of course using this code it is still your responsibility to hold and cancel your AsyncTasks instances in case of certain lifecycle events of your viewholders (Activites or Fragments). Using ViewModels makes it much easier but that is a different topic ;-)

mobile developer since 2002