Converting event listeners into streams using the Effect library involves creating a stream that ...

Hello! I've only started using effect and i like it so far, but I have some troubles converting parts of my codebase to it.

Can someone help me understand how to properly turn event listener into stream?

For context: listen function is from tauri api, it needs to be awaited in order to start calling callback given to it.

The code I had looked like this:

const unsubProgress = await listen<ProgressState>(
  'export_logs_progress',
  action(({ payload }) => {
    this.chunks += payload.progress;
    this.state = payload.state;
  })
);

const unsubFinished = await listen<SaveLogsResult>(
  'export_logs_finished',
  ({ payload }) => {
    unsubFinished();
    unsubProgress();

    match(payload)
      .with({ _result: 'success' }, (matched) => {
        this.state = 'export_logs_finished';
        defer.rs(matched);
      })
      .with({ _result: 'failure' }, (matched) => {
        defer.rj(matched);
      })
      .exhaustive();
  }
);


I've tried to turn this into Effect's
Stream
but I'm not sure how to do it properly.

Will this work?

const changes = Stream.async((emit) => {
  const unsubProgress = Effect.tryPromise(() =>
    listen<ProgressState>('export_logs_progress', ({ payload }) => {
      emit(Effect.succeed(Chunk.of(payload)));
    })
  );

  const unsubFinished = Effect.tryPromise(() =>
    listen<SaveLogsResult>('export_logs_finished', () => {
      emit(Effect.fail(Option.none()));
    })
  );
});
Was this page helpful?