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的更多相关文章

  1. [RxJS] Combining Streams with CombineLatest

    Two streams often need to work together to produce the values you’ll need. This lesson shows how to ...

  2. [RxJS] Refactoring Composable Streams in RxJS, switchMap()

    Refactoring streams in RxJS is mostly moving pieces of smaller streams around. This lessons demonstr ...

  3. RxJS入门2之Rxjs的安装

    RxJS V6.0+ 安装 RxJS 的 import 路径有以下 5 种: 1.创建 Observable 的方法.types.schedulers 和一些工具方法 import { Observa ...

  4. [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 ...

  5. [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 ...

  6. [RxJS] Sharing Streams with Share

    A stream will run with each new subscription added to it. This lesson shows the benefits of using sh ...

  7. [RxJS] Build your own RxJS

    JavaScript has multiple APIs that use callback functions that all do nearly the same thing with slig ...

  8. [rxjs] Throttled Buffering in RxJS (debounce)

    Capturing every event can get chatty. Batching events with a throttled buffer in RxJS lets you captu ...

  9. [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 ...

随机推荐

  1. jvm-初探

    目录 1,Java体系结构 2.jvm执行引擎 3,ClassLoader的体系结构 4,java class文件 概述 其实,学java不算新手了,但是却感觉很多基本的知识,我们一开始也许是记住而不 ...

  2. linux common command.

    Stopping & Starting shutdown -h now – Shutdown the system now and do not reboothalt – Stop all p ...

  3. How do I size a UITextView to its content?

    UITextView 自适应高度,搬来一篇stack上的:   Is there a good way to adjust the size of a UITextView to conform to ...

  4. 开始Swift之旅 - HelloWorld

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  5. JS中区分参数方法

    实现功能:在使用cocosjs制作游戏过程中,很多东西都可以重复使用,例如菜单栏等等.今天尝试写了一个自定义的Js文件用作菜单方便以后使用. 将菜单按钮,以及触发事件作为参数生成一个层 直接在游戏中使 ...

  6. 你好,C++(9)坐216路公交车去买3.5元一斤的西红柿——C++中如何表达各种数值数据 3.3 数值数据类型

    3.3  数值数据类型 从每天早上睁开眼睛的那一刻开始,我们几乎每时每刻都在与数字打交道:从闹钟上的6点30分,到上班坐的216路公共汽车:从新闻中说的房价跌到了100元每平米到回家买菜时的西红柿3. ...

  7. Semaphore (通常用于限制可以访问某些资源(物理或逻辑的)的线程数目)

    Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目.例如,下面的类使用信号量控制对内容池的访问: 方法详解: 构造方法摘要 Semaphore(int permits)     ...

  8. css expression explaination

    http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx 据说已经被弃用的IE css写法,为了修复一些IE8及老版本 ...

  9. 模块化的JavaScript开发的优势在哪里

    如今模块化的 JavaScript 的开发越来越火热,无论是模块加载器还是优秀的 JavaScript 模块,都是层出不穷.既然这么火,肯定是有存在的理由,肯定是解决了某些实际问题.很多没接触过模块化 ...

  10. ls命令解析

    ls 列出目录的内容.它可是我们所经常使用的命令,那么你了解它所有的功能吗?下面让我们来看看吧! 命令格式 ls [OPTION]... [FILE]... 参数说明 -a , --all 显示所有文 ...