Effect CommunityEC
Effect Community3y ago
13 replies
whatplan

Preventing Scope Merge in Multiple Scoped Resources

When accessing multiple scoped resources within a single Effect, is it possible to prevent these scopes from merging, and allow fine grained control on when each is closed?

const task1 = Effect.gen(function* (_) {
  yield* _(Console.log("thing 1"));
  yield* _(Effect.addFinalizer(() => Console.log("closing thing 1")));
});

const task2 = Effect.gen(function* (_) {
  yield* _(Console.log("thing 2"));
  yield* _(Effect.addFinalizer(() => Console.log("closing thing 2")));
});

const program = Effect.gen(function* (_) {
  yield* _(task1);
  yield* _(task2);
  // both of these scoped have now merged into 1
}).pipe(Effect.scoped);

await Effect.runPromise(program);
/*
thing 1
thing 2
closing thing 2
closing thing 1
*/

// id like to be able to do something like
// (very rough sudo code)
const program2 = Effect.gen(function* (_) {
  const scope1 = yield* _(task1, Effect.getScope);
  const scope2 = yield* _(task2, Effect.getScope);
}).pipe(
  Effect.scoped(scope1),
  Effect.zipRight(Console.log("doing something else")),
  Effect.scoped(scope2)
);

/*
thing 1
thing 2
closing thing 1
doing something else
closing thing 2
*/
Was this page helpful?