- Mastering Reactive JavaScript
- Erich de Souza Oliveira
- 251字
- 2021-07-09 20:33:08
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
- Windows Server 2019 Cookbook
- Getting Started with oVirt 3.3
- 阿里云數(shù)字新基建系列:云原生操作系統(tǒng)Kubernetes
- 蘋果電腦玩全攻略 OS X 10.8 Mountain Lion
- 嵌入式Linux系統(tǒng)開發(fā):基于Yocto Project
- 精通Linux內(nèi)核開發(fā)
- Ganglia系統(tǒng)監(jiān)控
- 玩到極致 iPhone 4S完全攻略
- Alfresco 4 Enterprise Content Management Implementation
- Windows 7中文版從入門到精通(修訂版)
- Kali Linux 2018:Windows Penetration Testing
- Linux命令行大全(第2版)
- OpenStack Essentials(Second Edition)
- 鴻蒙入門:HarmonyOS應用開發(fā)
- 完美應用Ubuntu(第4版)