flyd icon indicating copy to clipboard operation
flyd copied to clipboard

What's the motivation for ending a stream?

Open LAC-Tech opened this issue 4 years ago • 3 comments

Hi, long time user, first time writer.

Reading the docs again, I notice that there's a concept of ending a stream. What's the motivation for that? I can't think of a scenario, but I'm sure you had one in mind.

LAC-Tech avatar Apr 17 '21 03:04 LAC-Tech

Imagine you've got a timer and want to cancel it when listeners stop:

function interval(ms: number) {
  const s = stream()
  let i = 0;
  const interval = setInterval(()=> s(i++), ms)
  s.end.map(()=> clearInterval(interval))
  return s
}

interval(1000)
  .pipe(take(4))
// 1-2-3-4

This can be extrapolated for arbitrary cleanup logic for e.g. web sockets

nordfjord avatar Apr 17 '21 16:04 nordfjord

I assume take in the case must be aware of the additional protocol and has to actively close upstream interval when it's done. take probably also has to close itself so that an appropriate side-effect can be triggered. I this correct?

dehmer avatar Jul 03 '23 06:07 dehmer

That sounds about right. Some of the built-in modules propagate ending downwards using a pattern like

const takeUntil = (term, src) =>
  flyd.endsOn(
    flyd.merge(term, src.end),
    flyd.combine((src, self) => {
      self(src());
    }, [src])
  );

nordfjord avatar Jul 03 '23 12:07 nordfjord