Example of completable future

In below example, we

new CompletableFuture<Integer>().thenApplyAsync(new Function<Integer, String>() {
    @Override
    public String apply(Integer integer) {
        // Do some heavy task here
        return "Something returned from long task";
    }
}, Executors.newSingleThreadExecutor()).thenAcceptAsync(new Consumer<String>() {
    @Override
    public void accept(String s) {
        // Do something with result of previous task
    }
}).thenRunAsync(new Runnable() {
    @Override
    public void run() {
        // Do something after everything ends
    }
});

Here is another example in Android, how you can do some operation in background thread and return back to main thread when everything is completed.

new CompletableFuture<Integer>()
        .thenApplyAsync(integer -> "Something returned from long task", Executors.newSingleThreadExecutor())
        .thenAcceptAsync(s -> {
            System.out.println("Previous result on main thread: " + s);
        }, ContextCompat.getMainExecutor(context));

Last updated