Take the 2-minute tour ×

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 ...}

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


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

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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:


Here's a demo.

share|improve this answer
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

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( .. )
share|improve this answer
It'd be great to see an example of this. Is stopper just a Bus that you use for control flow? –  pdoherty926 Oct 25 at 19:13
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 5 at 19:38

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.

share|improve this answer

Your Answer


