Class 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) {

Using this class, the loop above becomes:

 R zero;, zero, (result, element, loop) -> {
     CompletableFuture<R> future = processAsync(element);
     future.whenComplete((r, x) -> {
         if (x == null) {
             R reduced = reduce(result, r);
             if (shouldIterate(r)) {
             } else {
         } else {
 }, Promise.complete((r, x) -> {
     // Process final result or failure.
  • Constructor Details

    • AsyncFoldLeft

      public AsyncFoldLeft()
  • Method Details

    • run

      public static <T, R> void run(T[] array, R zero, AsyncFoldLeft.Operation<T,R> operation, Promise<R> promise)
    • run

      public static <T, R> void run(Collection<T> collection, R zero, AsyncFoldLeft.Operation<T,R> operation, Promise<R> promise)

      Processes the given collection of elements.

      The initial result zero is returned if the collection is empty.

      For each element the operation function is invoked.

      The collection should have a "stable" iterator, i.e. it should not be affected if the collection is modified concurrently by another thread, or by the same thread in th operation during the iteration.

      Type Parameters:
      T - the type of element
      R - the type of the result
      collection - the elements to process
      zero - the initial result
      operation - the operation to invoke for each element
      promise - the promise to notify of the final result