0no-co / wonka

🎩 A tiny but capable push & pull stream library for TypeScript and Flow
MIT License
709 stars 29 forks source link

How to create a pull stream using `wonka`? #91

Closed Pet3ris closed 4 years ago

Pet3ris commented 4 years ago

Hi There,

I'm trying to create a stream that iterates down from a very high number. I can't use fromArray as there would be too many entries and I'm intending to cap them later. But effectively I'd like a stream that will only produce x, x-1, x-2 from a high starting point in pull fashion.

The make function for constructing new streams (https://wonka.kitten.sh/api/sources#make) seems to be push only. What's the way to build a pull/lazy stream?

Pet3ris commented 4 years ago
let naturals: Wonka.Types.sourceT(int) = {
  Wonka.Types.curry(sink => {
    let state: Wonka.trampolineT(int) = {
      ended: false,
      looping: false,
      pulled: false,
      current: 1,
    };

    sink(.
      Wonka.Types.Start(
        (. signal) =>
          switch (signal, state.looping) {
          | (Pull, false) =>
            state.pulled = true;
            state.looping = true;

            while (state.pulled && !state.ended) {
              let x = state.current;
              state.current = state.current + 1;
              state.pulled = false;
              sink(. Push(x));
            };
          | (Pull, true) => state.pulled = true
          | (Close, _) => state.ended = true
          },
      ),
    );
  });
};