Question

I know in .net, I can do something like this in a task,

task.ContinueWith((v) =>
        {
            Operation1();
        })

            .ContinueWith((V) =>
            {
                Operation2();
            },  

            Cancel.Token, TaskContinuationOptions.None, Scheduler);
        return task;

Or use the Aysnc/Await features to do the Operations one by one.

How can I do this in Java?

I have read the materials for AsyncTask, but the after the operation done in doInBackground, the method in onPostExecute(Result) are still be called synchronously.

So my question is How to operate a series of different function one by one?

Was it helpful?

Solution

If you are comfortable with Rx, you could use RxJava. It's not pretty, but it works:

final ExecutorService executor = Executors.newCachedThreadPool();

final ConnectableObservable<?> result = Observable.concat(
    Observable.defer(
        new Func0<Observable<?>>() {
            @Override
            public Observable<?> call() {
                return Observable.from(
                    executor.submit(
                        new Runnable() {
                            @Override public void run() { task(1); }
                        }
                    )
                );
            }
        }
    ),
    Observable.defer(
        new Func0<Observable<?>>() {
            @Override
            public Observable<?> call() {
                return Observable.from(
                    executor.submit(
                        new Runnable() {
                            @Override public void run() { task(2); }
                        }
                    )
                );
            }
        }
    )
).replay();

result.connect();

There is probably a better way to do this, but I don't know the RxJava APIs very well, as I use my own implementation of Rx for Java.

The gist is:

  1. The concat() operator joins multiple observable sequences in serial. In this case, each sequence is just a single element: the result of a task.
  2. The defer() operator prevents each task from being scheduled until someone subscribes. In this case, that happens when the preceding task/sequence terminates.
  3. The from() operator transforms a Future<?> into an Observable<?>.
  4. The replay() operator creates a connectable observable, ensuring that the sequence of tasks only executes once, even if there are multiple subscribers. The result will be captured so late subscribers will still receive it.
  5. Calling connect() kicks off the sequence of tasks.

OTHER TIPS

You could override the onPostExecute(result), which seems awkward compared to C#. You may opt to be an early adapter of Java 8 with lambdas, so you could implement the same syntax:

.ContinueWith(v -> operation1())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top