ayorosmage
ayorosmage

Reputation: 1737

How to perform sequential tasks having asynchronous subtasks

I am facing the following problem as part of my Android development:

I need to perform sequential tasks but my problem come from the fact that each task has asynchronous subtasks. Before executing the next task, I need to be sure the last task finished (that means, all asynchronous subtasks also finished).

I am planning to combine the followings solutions:

(1) ThreadPool with a fixed number of threads set to "1". However, that doesn't prevent the next task to be executed after each asynchronous subtasks has finished.

(2) BlockingQueue inside each task with a call to the blocking take() method that wait for a finished information from the asynchronous subtask.

I find this handmade method not very clean and error prone.

Anyone knows a better solution ? Or maybe a lib that solve elegantly this problem ?

Upvotes: 1

Views: 208

Answers (1)

Grisu47
Grisu47

Reputation: 552

You can leverage RxJava to easily do this:

Observable
    .concat(
        Observable.fromCallable(() -> yourAsyncTask1()),
        Observable.fromCallable(() -> yourAsyncTask2()))
    .subscribeOn(androidSchedulers.io())
    .observeOn(androidSchedulers.mainThread())
    .subscribe(() -> {
        doSomethingAfterBothFinished();
    });

RxJava even allows you to easily handle errors with onError.

If one task depends on the other you can use map:

Observable
    .fromCallable(() -> yourAsyncTask1())
    .map((ResultType1 result1) -> {
        return yourAsyncTask2(result1);
    })
    .subscribeOn(androidSchedulers.io())
    .observeOn(androidSchedulers.mainThread())
    .subscribe(() -> {
        doSomethingAfterBothFinished();
    });

Where result1 is the returned value from yourAsyncTask1().

Note that everything above subscribeOn() will be done on a background thread, wheres everything below observeOn() will be done on the mainThread. this is very helpful if you want to update your UI after the tasks finished, since that can only be done on the mainThread

Upvotes: 1

Related Questions