Zin Win Htet
Zin Win Htet

Reputation: 2565

How to do more than one AsyncTask one after another?

Let's say I've two AsyncTask. AsyncTask_A and AsyncTask_B. I want to execute AsyncTask_B only when AsyncTask_A is totally finished. I know one that I could execute AsyncTask_B in AsyncTask_A's postExecute() method. But.. is there any better way?

Upvotes: 0

Views: 384

Answers (2)

Changdeo Jadhav
Changdeo Jadhav

Reputation: 706

Queue<ASyncTask> q;
AsyncTask_A async_a;
AsyncTask_B async_b;
q.add(async_a);
q.add(async_b);

while(!q.empty)
{
  AsyncTask task = q.pop();
  task.execute();
  while(task.isRunning())
  {
    Thread.sleep(SOME_MILLISECONDS) // You can use wait and notify here.instead of sleep
  }
}

Upvotes: 0

Andrew Breen
Andrew Breen

Reputation: 695

In this instance you should create a class that acts a singleton that will handle queuing of these tasks (i.e. a list of AsyncTasks within it) where it tracks if any are running, and if they are, queues them instead. Then within the postExecute() of these tasks, all should callback to the queue object to notify them that they are completed, and then within this callback it should then run the next AsyncTask.

This will allow you to:

  1. Call AsyncTaskA without always having to run AsyncTaskB (removing the hard dependency)
  2. Add more AsyncTasks down the track because the dependency on managing these tasks is on the queue object instead of within the AsyncTasks

Upvotes: 1

Related Questions