Effect CommunityEC
Effect Community3y ago
6 replies
whatplan

Effectful Program with Ref, Fiber, and Schedule

const program = Effect.gen(function* (_) {
  const ref = yield* _(Ref.make(0));
  const fiber1 = yield* _(
    Ref.update(ref, (n) => n + 1),
    Effect.forever,
    Effect.fork
  );
  const fiber2 = yield* _(
    Ref.get(ref),
    Effect.flatMap((n) => Effect.log(`n = ${n}`)),
    Effect.repeat(Schedule.spaced("1 seconds")),
    Effect.fork
  );

  yield* _(Fiber.joinAll([fiber1, fiber2]));
});

timestamp=2023-10-24T22:29:59.708Z level=INFO fiber=#2 message="n = 1"
timestamp=2023-10-24T22:30:00.714Z level=INFO fiber=#2 message="n = 426192"
timestamp=2023-10-24T22:30:01.720Z level=INFO fiber=#2 message="n = 848286"
timestamp=2023-10-24T22:30:02.721Z level=INFO fiber=#2 message="n = 1268331"
...


Why does n first log as 1?
I would expect either:
- fiber 2 runs before fiber 1, when ref is still its initial value (0), and so logs one
or
- fiber 1 runs before fiber 2, loops until it gets paused at which point the counter is some value much higher than 1 when fiber 2 logs it
Was this page helpful?