Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How to Sync Two Async tasks?

Tags:

java

android

I need to combine two lists each of which is returned after its own separate Async Call. How does one best coordinate Async calls like these. Are there any standard SDK methods for waiting until another async task has completed?

like image 811
Code Droid Avatar asked Apr 23 '12 20:04

Code Droid


1 Answers

execute() call returns an instance of AsyncTask, you may save this instance to check later, if the task has finished or not by calling getStatus(), so your code will look like this:

final AsyncTask<...> first_task;
final AsyncTask<...> second_task;

public someMethod() {
    first_task = new MyFirstAsyncTask().execute();
    second_task = new MySecondAsyncTask().execute();
    // other things
}

private class MyFirstTask extends AsyncTask<...> {
    // business as usual

    protected void onPostExecute(SomeData[] result) {
        if( second_task != null && second_task.get_status() == AsyncTask.Status.FINISHED ) {
            // start the task to combine results
            ....
            //
            first_task = second_task = null;
        }
    }
}

private class MySecondTask extends AsyncTask<...> {
    // business as usual

    protected void onPostExecute(SomeData[] result) {
        if( first_task != null && first_task.get_status() == AsyncTask.Status.FINISHED ) {
            // start the task to combine results
            ....
            //
            first_task = second_task = null;
        }
    }
}

and the task, which finishes last, can start the new task to combine the results.

like image 192
lenik Avatar answered Oct 06 '22 10:10

lenik