Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I coordinate two background tasks?

Tags:

I have 2 AsyncTasks running in a fragment.
The AsyncTasks are defined in a different class and not inner private classes of the fragment.
The problem I have is that now it came up that I need for AsyncTaskX to wait until AsyncTaskY has finished its onPostExecute
How can I solve this?
I was thinking of using a countdownlatch but AsyncTaskY is in a different class and I am not sure what is the best way to code this?
Is there a way to check if an AsyncTask has finished completely?

Update:
I was wondering is task.execute().get() returning after the onPostExecute?

Update 2:
Is calling CountDownLatch.countDown() from UI thread safe?

like image 289
Jim Avatar asked Apr 20 '16 20:04

Jim


1 Answers

Is it really difficult to determine this without seeing your code. One dirty solution would be to add a static boolean and then add a recursive timer. This is not the best programming technique, but from what I read it would certainly work.

Create a static boolean in any class

static boolean onPostExecuteFinished;

in the the AsyncTask that needs to be finished first set it to true

ClassName.onPostExecuteFinished = true;

In the class that needs to wait you make a recursive method waiting for it to finish. I recommend using a handler.

public void nameOfRecursiveMethodHere()
Handler handler = new Handler()

handler.postDelated(new runnable........{
if (ClassName.onPostExecuteFinished) {
//Great it is finished do what you need
} else {
//Not finished call this method again
nameOfRecursiveMethodHere();
}

}),(put how often you want it to check in milliseconds here);
like image 92
fsebek Avatar answered Sep 28 '22 02:09

fsebek