paldepind / flyd

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

flyd.off(fn, s) ? #127

Closed leeoniya closed 7 years ago

leeoniya commented 7 years ago

Hi,

is there a way to unsubscribe a side-effect handler registerd via flyd.on(fn, s).

The situation is this: I have a view layer which renders the stream value on view.redraw(). When that function enconters a stream in its template, it registers itself via flyd.on so that follow-up redraws can be reactive to the stream if it's modified externally. This works fine.

However, on any given redraw this stream may no longer come back in the template, so i must de-register the side-effect handler as the view no longer depends on this stream. How would i do this?

thanks!

leeoniya commented 7 years ago

btw, i got around this by not using on but rather re-creating a self-ending dependent stream on each redraw call. seems like a cleaner solution.

c-dante commented 7 years ago

On returns a stream that can be used to end the registration.

const s = flyd.stream(0);
const endDebugS = flyd.on((x) => console.debug(x), s);
s(0)(1)(2)(3);
endDebugS.end(true);
s(4)(5)(6);
console.debug(s());

From the docs:

flyd.on(fn, stream) Similar to map except that the returned stream is empty. Use on for doing side effects in reaction to stream changes. Use the returned stream only if you need to manually end it.

leeoniya commented 7 years ago

thanks @c-dante , much cleaner.