Class AsyncFoldLeft

java.lang.Object
org.cometd.common.AsyncFoldLeft

public class AsyncFoldLeft extends Object

Processes asynchronously a sequence of elements, producing a result that is the reduction of the results produced by the processing of each element.

This class implements the asynchronous version of the following synchronous for loop, but where the processing of each element may be asynchronous.


 R result;
 for (T element : list) {
     (result, proceed) = operation.apply(result, element);
     if (!proceed) {
         break;
     }
 }
 

Using this class, the loop above becomes:


 R zero;
 AsyncFoldLeft.run(list, zero, (result, element, loop) -> {
     CompletableFuture<R> future = processAsync(element);
     future.whenComplete((r, x) -> {
         if (x == null) {
             R reduced = reduce(result, r);
             if (shouldIterate(r)) {
                 loop.proceed(reduced);
             } else {
                 loop.leave(reduced);
             }
         } else {
             loop.fail(x);
         }
     })
 }, Promise.complete((r, x) -> {
     // Process final result or failure.
 });