paldepind / flyd

The minimalistic but powerful, modular, functional reactive programming library in JavaScript.
MIT License
1.56k stars 84 forks source link

What's the motivation for ending a stream? #216

Open LAC-Tech opened 3 years ago

LAC-Tech commented 3 years ago

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.

nordfjord commented 3 years ago

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

dehmer commented 1 year ago

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?

nordfjord commented 1 year ago

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])
  );