[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 ...
随机推荐
- (一)SAPI简述
SAPI,软件中的语音技术包括两方面的内容,一个是语音识别(speech recognition) 和语音合成(speech synthesis).这两个技术都需要语音引擎的支持. 下面我们来了解下基 ...
- 使用<pre>标签为你的网页加入大段代码
在上节中介绍加入一行代码的标签为<code>,但是在大多数情况下是需要加入大段代码的,如下图: 怎么办?不会是每一代码都加入一个<code>标签吧,没有这么复杂,这时候就可以使 ...
- WPF 依赖属性与依赖对象
在介绍依赖属性之前,我先介绍下属性的历史 属性的历史: 早期C++的类中,只有字段及方法,暴露数据靠的是方法, 但是字段直接暴露会不安全,所以才用方法来暴露,在设置的时候加些约束,在MFC中 ...
- 05_Smart-image通过SoftReference提高性能
文章导读: 文件介绍了常见的图片下载开源插件smart-image, 由于移动设备硬件受限,因此Android的相关app都要考虑到性能的关系, 所以很多的第三方插件都使用到了缓存cache技术,本人 ...
- Hibernate中session的产生的方式
* session的产生的方式 * 1. sessionFactory.openSession 每次都会新创建一个session,只要新创建一个session,hiber ...
- hdu1142 A Walk Through the Forest( Dijkstra算法+搜索)
看到这道题,想起了我家旁边的山! 那是一座叫做洪山寨的山,据说由当年洪秀全的小妾居住于此而得名! 山上盛产野果(很美味)! 好久没有爬上去了! #include<stdio.h> #inc ...
- Python标准库--os模块
这个模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行.一个例 ...
- 【jquery学习笔记】关于$(window),$("html,body").scroll()的在不同浏览器的不同反应
已经很几次碰到了这种问题, 例子: $(window).scroll(function(){ var num=$(window).scrollTop(); //之前的写法是$ ...
- C#委托基础
转载自 http://woshixy.blog.51cto.com/5637578/1070976 C#委托基础1——委托基础 委托和其委托的方法必须具有相同的签名.签名相同:1.参数类型 ...
- jquery ajax (2)实例 .GET
1js 代码 $(function(){ $("#send").click(function(){ $.get("get3.php", { username : ...