Java – The right way to link 2 asynchronous tasks in android

The right way to link 2 asynchronous tasks in android… here is a solution to the problem.

The right way to link 2 asynchronous tasks in android

I have two asynchronous tasks, Task 1 and Task 2.

I need to run Task 1 before Task 2

, but I don’t want to couple the two tasks by calling Task 2 in Task 1’s onPostExecute implementation; Because I used task 1 alone in other cases.

Is there a way for me to define two async tasks without binding (bind) to each other and chaining them together in specific cases?

Thank you very much for your help.

Solution

You can try something like this:

final Executor directExecutor = new Executor() {
  public void execute(Runnable r) {
    r.run();
  }
};
AsyncTask.execute(new Runnable() {
  task1.executeOnExecutor(directExecutor, params1);
  task2.executeOnExecutor(directExecutor, params2);
});

I

don’t have an android SDK on my machine right now, so I can’t verify.

Related Problems and Solutions