Mastering Reactive JavaScript
上QQ阅读APP看书,第一时间看更新

Observables' lazy evaluation

In bacon.js, an observable doesn't emit any event unless someone is subscribed to listen to it. We can easily check this behavior using doAction(). This operator lets us run an arbitrary function every time an event is emitted from an observable.

If you create an observable from an array and add a doAction() operator to log your events then, without a subscription, it will print nothing to the console. So if you run the following code, you will see your program doesn't give you any output:

Bacon 
.fromArray([1,2,3])
.doAction((value)=>
console.log('running doAction')
);

As you can see in this code, we have no subscriber for the EventStream. This is why no event is emitted. However, if we add a subscriber to this EventStream, we will see the program print running doAction for each value:

Bacon 
.fromArray([1,2,3])
.doAction((value)=>
console.log('running doAction')
)
.log();

The preceding code gives you the following output:

    running doAction
1
running doAction
2
running doAction
3
<end>
It is really important to keep this behavior in mind because ignoring this can lead to bugs that are really hard to identify.