I have been using AsyncTask in Android for some time now. At the beginning, every time a task should be run asynchronously, I bundled its code into and 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), but now I feel my code is cluttered by so much boilerplate code (the AsyncTask skeleton), and AsyncTasks are sometimes executed inside code run asynchronously and Android may complain.
In particular, I am searching a way to modularly choose whether a task should be run asynchronously, after another, 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));
runTask(new MySecondParallelTask(mySecondData));
runTask(new MyFirstSequentialTask(myThirdData, new MySecondSequentialTask(myFourthData, new DummyCallback())));
}
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 asynchronous tasks in Android?
Aucun commentaire:
Enregistrer un commentaire