2

I'm learning to use the fantastic Bacon.js library for functional reactive programming. Adding handlers to a property or stream is easy:

handler = function(value){... do something ...}
property.onValue(handler)

Say somewhere down the line I want to cancel this subscription, like this (pseudocode):

property.unsubscribe(handler)

Is there a way to do this with Bacon.js?

jpadvo
  • 6,031
  • 3
  • 26
  • 30

3 Answers3

11

Both answers above are correct. Personally, I've never used either solution though. In fact, they mainly exist for internal purposes and for writing custom combinators and integrations.

So instead I recommend combinators like take, takeWhile and takeUntil. In an FRP application, the signal that triggers the need can usually be modeled as an EventStream. In that case you can do

var data, stopper // EventStreams
data.takeUntil(stopper).onValue( .. )
raimohanska
  • 3,265
  • 17
  • 28
  • It'd be great to see an example of this. Is `stopper` just a `Bus` that you use for control flow? – pdoherty926 Oct 25 '14 at 19:13
  • 3
    Well for example, if you want to react to mouse moves and stop that when a key is pressed, you'll do `mouseMoves.takeUntil(keyPress).onValue(..)`. Or if you want to react only once, you'll do `clicks.take(1).onValue(..)`. – raimohanska Nov 05 '14 at 19:38
3

From the "cleaning up" section of the docs:

Call the dispose() function that was returned by the subscribe() call.

So you have to save the return of onValue:

var dispose = property.onValue(handler)

Then invoke it to remove the listener:

dispose();

Here's a demo.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Thank you McGarnagle! I know it had to be somewhere, but for the life of me I couldn't see it. :) – jpadvo Oct 11 '13 at 23:19
1

From the documentation:

stream.subscribe(f) subscribes given handler function to event stream. Function will receive Event objects (see below). The subscribe() call returns a unsubscribe function that you can call to unsubscribe. You can also unsubscribe by returning Bacon.noMore from the handler function as a reply to an Event.

Vidya
  • 29,932
  • 7
  • 42
  • 70