Android How to sync two Async tasks?

I need to combine two lists, each of which returns after its own Asynchronous call. How to best coordinate such Async challenges. Are there any standard SDK methods for waiting for another async task to complete?

+6
source share
3 answers

execute() call returns an AsyncTask instance, you can save this instance for verification later if the task is completed 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 a task that ends last can start a new task to combine the results.

+5
source

Java has nice things like Future class and the like. It makes no sense to describe this structure here, there are many resources on the network. It is better to have at least one asynchronous task, in any case there is no need to run two asynchronous programming tasks simultaneously. You can do both parts in one doInBackground

0
source

It really depends on the need.

Do you need to wait until all data appears? If you are not just making a call to your function with a synchronized block function in your activity

If so, do you expect them to work only once; why two (or X) as a whole? maybe you can check: CoundDownLacth (http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html)

0
source

Source: https://habr.com/ru/post/913975/


All Articles