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

Changes in an observable

In the last section, we saw how to use the scan() method to create a Property from an EventStream. When we use this method (actually, when we use any operator), we do not change the original observable; we always create a new observable. So, it never interferes with the other subscriptions (and transformations) of the observable. We can change the previous code to listen to events on both the EventStream and the Property; now we will see that making changes in one of these two doesn't affect the other:

var eventStream = Bacon 
.sequentially(100,['a','b','c','d']);

eventStream.onValue((value)=>{
console.log('From the eventStream :'+value);
});

var property = eventStream.scan('=> ',(acc,b)=> acc+b);

property.onValue((value)=>{
console.log('From the property :'+value);
});

It gives the following output:

    From the property :=>
From the eventStream :a
From the property :=> a
From the eventStream :b
From the property :=> ab
From the eventStream :c
From the property :=> abc
From the eventStream :d
From the property :=> abcd

This shows that the usage of the scan() method to concatenate the array in the Property does not change the behavior of the original eventStream.