[RxJS] Combining streams in RxJS
Source: Link
We will looking some opreators for combining stream in RxJS:
- merge
- combineLatest
- withLatestFrom
- concat
- forkJoin
- flatMap / switchMap
Merge:
Observable.merge
behaves like a "logical OR" to have your stream handle one interaction OR another.
let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2"); let btn1Click$ = Rx.Observable.fromEvent(btn1, "click");
let btn2Click$ = Rx.Observable.fromEvent(btn2, "click"); let btn1Log$ = btn1Click$.map( (ev) => {
console.log("Button 1 clicked");
});
let btn2Log$ = btn2Click$.map( (ev) => {
console.log("Button 2 clicked");
});
let clicks$ = Rx.Observable.merge(btn1Log$, btn2Log$); clicks$.subscribe();
combineLatest:
Ofter used when one of streams value changed, then produce a side effect:
var source1 = Rx.Observable.interval(1000)
.map(function (i) { return 'First: ' + i; }); var source2 = Rx.Observable.interval(2000)
.map(function (i) { return 'Second: ' + i; }); // Combine latest of source1 and source2 whenever either gives a value
var source = Rx.Observable.combineLatest(
source1,
source2
).take(4); var subscription = source.subscribe(
function (x) {
console.log(x);
},
function (err) {
console.log('Error: %s', err);
},
function () {
console.log('Completed');
}); /*
["First: 0", "Second: 0"]
["First: 1", "Second: 0"]
["First: 2", "Second: 0"]
["First: 2", "Second: 1"]
"Completed"
*/
withLatestFrom:
var source1 = Rx.Observable.interval(1000)
.map(function (i) { return i; }); var btn = document.querySelector("#btn");
var source2 = Rx.Observable.fromEvent(btn, "click"); var source =source1
.withLatestFrom(
source2,
(source1, click) => ({timer: source1, clicks: click.x})
).take(4); var subscription = source.subscribe(
function (x) {
console.log(x);
},
function (err) {
console.log('Error: %s', err);
},
function () {
console.log('Completed');
});
Read the difference between combineLatest and withLatestFrom: Link.
concat:
Concat will combine two observables into a combined sequence, but the second observable will not start emitting until the first one has completed.
let first = Rx.Observable.interval(1000).take(3).do( (i) => { console.log("First: ", i);}); let second = Rx.Observable.interval(500).take(3).do( (i) => { console.log("Second: ", i);}); first.concat(second).subscribe(); /*
"First: "
0
"First: "
1
"First: "
2
"Second: "
0
"Second: "
1
"Second: "
2
*/
forkJoin:
We use forkJoin to execute observables in parallel. One common use case of this is making multiple http requests in parallel. In my sample I am forkJoining two very simple observables, but the key point is that the subscriber won't receive any values until both observables have completed.
let first = Rx.Observable.interval(1000).take(6); let second = Rx.Observable.interval(500).take(3); Rx.Observable.forkJoin(first, second).subscribe(
(res) =>{
console.log(res); // [5, 2]
},
(err) => {
console.log(err);
},
() => {
console.log("Completed"); // Completed
}
);
flatMap / switchMap
flatMap and switchMap basic are the same.
Just switchMap only care about the latest value, will ignore the previous value. So good to use with http reuqest.
The reason to use flatMap is because inside Observable you migth return another Observable, such as:
var btn = document.querySelector("#btn"); var click$ = Rx.Observable.fromEvent(btn, "click"); var promise$ = Rx.Observable.fromPromise( jquery.http('xxx'));
var xhrCall$ = click$.flatMap( () => {
return promise$;
}); xhrCall$.subscribe( (res) => {
console.log(res);
})
Inside Observalbe return another Observable, will create a 2-d Observable, just like inside map ruturn another array, will create 2-d array.
So we need to flatten it.
[RxJS] Combining streams in RxJS的更多相关文章
- [RxJS] Combining Streams with CombineLatest
Two streams often need to work together to produce the values you’ll need. This lesson shows how to ...
- [RxJS] Refactoring Composable Streams in RxJS, switchMap()
Refactoring streams in RxJS is mostly moving pieces of smaller streams around. This lessons demonstr ...
- RxJS入门2之Rxjs的安装
RxJS V6.0+ 安装 RxJS 的 import 路径有以下 5 种: 1.创建 Observable 的方法.types.schedulers 和一些工具方法 import { Observa ...
- [RxJS] Aggregating Streams With Reduce And Scan using RxJS
What is the RxJS equivalent of Array reduce? What if I want to emit my reduced or aggregated value a ...
- [Recompose] Handle React Events as Streams with RxJS and Recompose
Events are the beginning of most every stream. Recompose provides a createEventHandler function to h ...
- [RxJS] Sharing Streams with Share
A stream will run with each new subscription added to it. This lesson shows the benefits of using sh ...
- [RxJS] Build your own RxJS
JavaScript has multiple APIs that use callback functions that all do nearly the same thing with slig ...
- [rxjs] Throttled Buffering in RxJS (debounce)
Capturing every event can get chatty. Batching events with a throttled buffer in RxJS lets you captu ...
- [RxJS] Stream Processing With RxJS vs Array Higher-Order Functions
Higher order Array functions such as filter, map and reduce are great for functional programming, bu ...
随机推荐
- 在浏览器运行 java applet时遇到的一些问题及其解决方法
运行 java applet时提示:您的安全设置已阻止本地应用程序运行,如何解决?如下图所示 这时候通过设置java的安全级别就可以了. 控制面板->程序->Java->安全 将安全 ...
- When Colon Scripting is comming (脚本最佳体验)
当冒号脚本来临-- 脚本最佳体验 冒号指派 说明; 冒号替代等号指派赋值,当命名声明指派时指定.相当于声明当前作用域的一个名字指派. 当对指定对象的属性赋值时候,依旧请使用等号.即不废弃等号赋值功用, ...
- FindBugs的Bug类型及分析
FindBugs分析记录 Bad Practice: Class defines a clone() method but the class doesn't implement Cloneable. ...
- 04_RHEL7.1忘记root密码
在开机进入启动项时,选择需要重设密码的那个启动项 按e进入编辑模式,找到rhgb和quiet参数(几乎在最下面),替换为 init=/bin/sh 按ctrl+X不需密码进入shell 以rw的方式重 ...
- 关于一个隐藏和显示物品列表的demo
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...
- [Git]更新远程代码到本地仓库
1. 查看远程仓库 $ git remote -v 2.从远程获取最新代码到本地 $ git fetch origin master 3.比较代码 $ git log -p master.. orig ...
- 《30天自制操作系统》读书笔记(2)hello, world
让系统跑起来 要写一个操作系统,我们首先要有一个储存系统的介质,原版书似乎是06年出版的,可惜那时候没有电脑,没想到作者用的还是软盘,现在的电脑谁有软驱?不得已我使用一张128M的SD卡来代替,而事实 ...
- Neutron网络-OPENSTACK讲得比较透和方便
http://www.ustack.com/blog/neutron_intro/ Neutron是OpenStack核心项目之一,提供云计算环境下的虚拟网络功能.Neutron的功能日益强大,并在H ...
- -_-#【Angular】工具函数
AngularJS学习笔记 上下文绑定 var f = angular.bind({a: 'xx'}, function() { console.log(this.a) }) f() // 'xx' ...
- (2015年郑州轻工业学院ACM校赛题)I 旋转图像
矩阵旋转,写一个转 90° 的函数就行了, 注意每次要将 长和宽的值进行交换就行了. #include<stdio.h> #include<iostream> #include ...