Optimizing Boolean Effect Execution: Immediate True Return or Final False

I have multiple effects that return booleans, they cannot be batched, they are uninterruptible and they may take different amounts of time to resolve
I want to execute them all and get back true as soon as any of them returns true, or false if they all return false

what is the best way to do this?
https://tsplay.dev/wXLoJw
import { Effect, Function, Queue } from "effect";

declare const getFlag: Effect.Effect<boolean>;
const requests = [getFlag, getFlag, getFlag];

// 1. all
const all = Effect.gen(function* () {
  const flagValues = yield* Effect.all(requests, {
    concurrency: "unbounded",
  });
  return flagValues.some(Function.identity);
  // requires waiting for all requests to complete
});

// 2. raceAll
const raceAll = Effect.gen(function* () {
  const firstResult = yield* Effect.raceAll(requests);
  if (firstResult) {
    return true;
  } else {
    // .. well what do we do now? we still need to check the others
    return;
  }
});

// 3. my 'solution'
const usingQueue = Effect.gen(function* () {
  const resultQueue = yield* Queue.unbounded<boolean>();
  yield* Effect.all(
    requests.map((request) =>
      request.pipe(
        Effect.flatMap((response) => Queue.offer(resultQueue, response)),
      ),
    ),
    {
      concurrency: "unbounded",
    },
  ).pipe(Effect.ensuring(Queue.shutdown(resultQueue)));

  const tryToPullOffQueue = Queue.isShutdown(resultQueue).pipe(
    Effect.flatMap((result) =>
      result ? Effect.succeed(null) : Queue.take(resultQueue),
    ),
  );

  const result = yield* tryToPullOffQueue.pipe(
    Effect.repeat({
      while: (output) => {
        if (output === null) {
          return true;
        } else {
          return !output;
        }
      },
    }),
  );

  if (result === null) return false;
  else return result;
});
Was this page helpful?