Effect CommunityEC
Effect Community3y ago
6 replies
Joshua

Making Layer Construction Lazy

Seems layer construction is eager, how can it be made lazy i.e upon request

My initial assumption was layers are constructed when requested. But seems that's not the case, for example

const Tag = Context.Tag<number>();

// the same applies to Effect.suspend
const tag = Layer.effect(
  Tag,
  Effect.gen(function* (_) {
    yield* _(Effect.log("constructing..."));
    const num = Math.random();
    yield* _(Effect.log("layer constructed"));
    return num
  })
);

const prog = Effect.gen(function* (_) {
  yield* _(Effect.log("starting..."));
  // I assumed layer Tag will only get constructed when requested here or anywhere else. The layer still gets constructed even when not used i.e if I comment out the line below
  const num = yield* _(Tag);
  yield* _(Effect.log("running..." + num));
});

prog.pipe(Effect.provide(tag), Effect.runFork)
Was this page helpful?