baconjs / bacon.js

Functional reactive programming library for TypeScript and JavaScript

Home Page:https://baconjs.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

are .end() & unsubscribe() redundant? [begginer]

Crul opened this issue · comments

Hi, I'm starting with FRP and I'm giviing Bacon.js a try.

I'm dealing with the basic things and I'm confused with the responsability of ending the subscriptions. (With the code below) I'm pretty sure [1] and [2] do the same (is that true?).

The question is if you need one of them to cancel the subscription when the stream ends, or the End event is enough

Thanks.
(I don't know how to mark the issue as a question, I think I have no rights to do it)

var bus = new Bacon.Bus();
var unsubscribe = stream.subscribe(onEvent);
stream.onEnd(unsubscribe); // [1]

function onEvent(event) {
    if (event.isNext()) {
        // do stuff
    } else if (event.isEnd()) {
        unsubscribe(); // [2]
    }
}

bus.push('new value');
bus.end();

Sorry for the short answer.

Unsubscribing from the stream (the consumer end), and ending the stream (producer end) are very different; yet related.

Unsubscribing from the stream doesn't end it. If there are other subscribers, they will still get events from the stream. As the (some) streams are lazy, they'll stop to produce events, if there aren't any any subscribers.

If the stream ends, then every subscriber will be unsubscripted automatically, as there no point to be subscribed. So in your example, both [1] and [2] are wrong (at least: not necessary). The ability to end the stream from producer end, and the propagation of auto-unsubscriptions are the differences from classical Observator pattern.

var bus = new Bacon.Bus();
bus.onNext(onNext);

function onEvent(x) {
  // do stuff
}

bus.push('new value');
bus.end(); // will do the cleanup 

To the end: Most likely, if you have to manage subscriptions manually (i.e. unsubscribe manually), you're doing something wrong (i.e. not idiomatic).

Thanks a lot!
I started feeling like if I was understanding something, and for a moment everything looks very easy... and it is! 👍

I like FRP.

P.S:: should I close the issue?

If the question is answered. Go ahead, and close.

Hi @Crul,

Great question. If you have more, please consider asking the at StackOverflow with the bacon.js tag. This helps other bacon users who might have the same question.

Philip