traverseIterablePar<R, E, A, B> static method

ZIO<R, E, IList<B>> traverseIterablePar<R, E, A, B>(
  1. Iterable<A> iterable,
  2. ZIO<R, E, B> f(
    1. A _
    )
)

Traverse an Iterable with the given function, collecting the results in parallel.

Implementation

static ZIO<R, E, IList<B>> traverseIterablePar<R, E, A, B>(
  Iterable<A> iterable,
  ZIO<R, E, B> Function(A _) f,
) =>
    ZIO.from((ctx) {
      if (iterable.isEmpty) {
        return Exit.right(IList());
      }

      final failure = Deferred<E, Never>();
      final results = iterable
          .map((a) => f(a)
              .tapErrorCause((_) => failure.failCause(_))
              .race(failure.await())
              .unsafeRun(ctx))
          .toList(growable: false);
      final hasFuture = results.any((eb) => eb is Future);

      if (!hasFuture) {
        return Either.sequenceList(
          results.cast<Exit<E, B>>().toList(growable: false),
        ).map((a) => a.toIList());
      }

      return Future.wait(results.map((eb) => Future.value(eb))).then(
        (eithers) => Either.sequenceList(eithers).map((a) => a.toIList()),
      );
    });