I have been using AsyncTask
in Android for some time now. I like it because you can run asynchronously, on a background thread, any task you want (by task I mean a block of code).
At the beginning, every time a task should be run asynchronously and/or on a background thread, I bundled its code into an extension of AsyncTask
. I sometimes needed to chain multiple of these tasks (one depending on the result of another) and called the next one in AsyncTask.onPostExecute(T data)
(once the execution finished), but now I feel my code is cluttered by so much boilerplate code (the AsyncTask skeleton) and the coupling of successive tasks.
On top of that, my AsyncTasks are sometimes launched from another AsyncTask and Android may complain. For example if I want to display some elements in the pre/post executions, this would be a problem when nesting the calls.
In particular, I am searching a way to modularly choose whether a task should be run synchronously/asynchronously, sequentially/in parallel, or together with another. My choice so far has been to have a simple interface Task
expecting an implemented execute(T data)
method. Then I can bundle one or multiple of them, to run sequentially or in parallel, as defined in blocks such as this one:
public doMultipleActions() {
runTask(new MyFirstParallelTask(myFirstData)); // running asynchronously in parallel the first task
runTask(new MySecondParallelTask(mySecondData)); // running asynchronously in parallel the second task
runTask(new MyFirstSequentialTask(myThirdData, new MySecondSequentialTask(myFourthData, new DummyCallback()))); // running asynchronously sequentially the third and fourth tasks
}
i.e. runTask(Task t)
will run the code of Task.execute(T data)
into a AsyncTask.doInBackground(T... data)
block of code. Sequential tasks also expect another task to be executed in a AsyncTask.onPostExecute(T data)
code block.
I have looked at multiple similar questions: Can I chain async task sequentially (starting one after the previous asynctask completes), AsyncTask chaining in Activity (callback?), How to avoid chaining several AsyncTask calls?, most approaching my issue but I could not find anything useful, even though I do not think I am the only one to deal with this.
Is there a better way, an expected way, or even a design pattern on modular usage of AsyncTask
in Android?