官术网_书友最值得收藏!

Subscribing using the onValue() method

The most common way of subscribing to an observable is using the onValue() method. This method has the following signature:

observable.onValue(functionToBeCalledWhenAnEventOccurs); 

So let's subscribe to eventStream to log every event on this stream, as follows:

Bacon 
.fromArray([1,2,3,4,5])
.onValue((number)=>console.log(number));

This code gives you the following output to the console:

    1
2
3
4
5

This function can be used for any type of observable (EventStream and Property). The only difference is that in Properties, if the initial value of the Property exists, then it triggers the onValue() function. Check out the following code:

var initialValue =0; 
Bacon
.fromArray([1,2,3,4,5])
.toProperty(initialValue)
.onValue((number)=>console.log(number));

This will give you the following output:

    0
1
2
3
4
5

When subscribing to an observable, it's important you know a way to unsubscribe it as well. The onValue() method returns a function; this function when called will unsubscribe your function from this observable. So we can create an observable from an interval and print a message every time an event is propagated, as follows:

Bacon 
.interval(1000)
.onValue(()=>(console.log("event happened")));

It will print the message event happened every second until we kill the process. But if we want, we can use the return of onValue() to unsubscribe from our observable after a certain amount of time, as follows:

var unsubscribe = Bacon 
.interval(1000)
.onValue(()=>(console.log("event happened")));

setTimeout(function(){
console.log("unsubscribing")
unsubscribe();
},4000);

With this code, the program will unsubscribe from your observable. This way, it exits normally and prints the following output:

    event happened
event happened
event happened
unsubscribing
主站蜘蛛池模板: 锡林郭勒盟| 绥江县| 宁津县| 酒泉市| 水富县| 绿春县| 南江县| 建昌县| 普格县| 盱眙县| 金坛市| 瑞昌市| 哈巴河县| 德钦县| 莲花县| 诏安县| 南溪县| 衡南县| 白水县| 东辽县| 红桥区| 永康市| 崇左市| 曲水县| 阿巴嘎旗| 广平县| 聂荣县| 唐海县| 赣州市| 翁牛特旗| 安丘市| 宁阳县| 通海县| 高陵县| 义马市| 泽普县| 察雅县| 丰原市| 陵水| 永登县| 玛多县|