Shi
Shi

Reputation: 520

Wait for the result of both two asnyc task

I have two asyctask that are called at the same time, but I need both two asynctask results to process the next step.

I have one solution: Given two member variable to check the return state of two async task:

boolean b1 = false;
boolean b2= false;
Result r1 = null;
Result r2 = null;

callback1(
   done(Result r){
        b1 = true;
        r1 = r;
        asyncTwoFunction(b1,b2)
}
)

callback2(
   done(Result r){
        b2 = true;
        r2 = r;
        asyncTwoFunction(b1,b2)
}
)

asyncTwoFunction(b1,b2){
    if(b1 && b2){
         doSomeThing(r1,r2);
         b1 = false;
         b2 = false;
    }
}

Are there some better way to do this? Thanks

Upvotes: 1

Views: 75

Answers (2)

kris larson
kris larson

Reputation: 30985

You can run two AsyncTasks and coordinate them, but the thread executor works in serial mode by default and will run them one after the other anyway. So why write code that jumps through hoops to sync the tasks and cause more bugs?

I would just have a single AsyncTask that does the work of both tasks in one background operation.

Upvotes: 0

siva
siva

Reputation: 1858

OnPostexecute of AsyncTask will be called on main thread once AsyncTask finishes its job. Since the final callback will be on main thread it is easy to monitor the state of each asynctask by calling get status on each asynctask. get status()

Upvotes: 2

Related Questions