Skip to content

CompletableFutures

johnmcclean-aol edited this page Nov 22, 2016 · 1 revision

The CompletableFutures class contains a lot of useful static methods for working with JDK CompletableFuture types. These functions are available directly on the cyclops-react FutureW type.

Sequence

A sequence operation takes a List / Stream / Collection of CompletableFutures and returns an CompletableFuture with a List / Stream / Collection of values. A Failed CompletableFuture in the sequence will result in a failed CompletableFuture result

E.g.

CompletableFuture<Integer> ten = CompletableFuture.completedFuture(10);
CompletableFuture<Integer> error = FutureW.ofError(new NoSuchElementException())
                                           .getFuture();

CompletableFuture<ReactiveSeq<Integer>> futures = CompletableFutures.sequence(Stream.of(ten, error, CompletableFuture.of(1)));
//CompletableFuture[NoSuchElementException];

And with no Failure

CompletableFuture<Integer> ten = CompletableFuture.completedFuture(10);
CompletableFuture<Integer> twenty = CompletableFuture.completedFuture(20);

CompletableFuture<ReactiveSeq<Integer>> futures = CompletableFutures.sequence(Stream.of(ten, twenty, CompletableFuture.of(1)));
//CompletableFuture[ReactiveSeq[10,20,1]];

Accumulate Success

An alternative to sequence is to accumulate only the CompletableFutures that have completed successfully.

In this example we can use the String concatonation Monoid to concat the the present CompletableFuture values.

CompletableFuture<String> just = CompletableFuture.completedFuture("10");
CompletableFuture<String> none = FutureW.ofError(new NoSuchElementException())
                                        .getFuture();
        
CompletableFuture<String> fts = CompletableFuture.accumulatePresent(Monoids.stringConcat,ListX.of(just, none, CompletableFuture.completedFuture("1")), 
                                                     );
//CompletableFuture.completedFuture("101")

Zip and combine

We can use Zip to combine an CompletableFuture with an Iterable or reactive-streams Publisher. Similarly we can use combine to combine an CompletableFuture with another CompletableFuture or cyclops-react Value type.

e.g.

CompletableFutures.zip(CompletableFuture.completedFuture(10),Arrays.asList(20), this::add)
//CompletableFuture[30]
 
private int add(int a, int b) {
            return a + b;
}
CompletableFutures.combine(CompletableFuture.completedFuture(10),CompletableFuture.completedFuture(20), this::add)
//CompletableFuture[30]

private int add(int a, int b) {
       return a + b;
}
Clone this wiki locally