Effect CommunityEC
Effect Community4mo ago
11 replies
sbs

Implementing a Polling Pattern with Effect and Atoms

I'm struggling with how to set up a polling pattern. I'd like to do something like:

const jobsAtom = ApiClient.runtime.fn(
  Effect.fnUntraced(function* (referenceId: string) {
    const client = yield* ApiClient;
    return yield* Stream.repeat(
      Effect.gen(function* () {
        yield* Effect.logInfo("poll");
        return yield* client.job.listJobs({
          urlParams: {
            referenceId,
          },
        });
      }),
      Schedule.spaced("1 seconds"),
    );
  }),
);


and then

// ...
const latestResult = useAtom(jobsAtom(arg));


The documentation on this is rather sparse. I've also tried different approaches to the one above, such as

const jobsAtom = (referenceId: string) =>
  ApiClient.runtime.pull(
    Stream.repeat(
      Effect.gen(function* () {
        const client = yield* ApiClient;
        yield* Effect.logInfo("poll");
        return yield* client.job.listJobs({
          urlParams: {
            referenceId,
          },
        });
      }),
      Schedule.spaced("1 seconds"),
    ),
  );


and


  const [stableAtom] = useState(jobsAtom(routeData.referenceId));
  const [jobs, go] = useAtom(stableAtom);

where the stable reference seems to be required or I just get infinite rerenders recreating the atom, but this still doesn't work since it only logs poll once.
Was this page helpful?