RxJS

理解Rx的关键是要把任何变化想象成事件流,当我们进行RxJS操作进行测试的时候,可以利用vscode进行代码测试,我们也可以利用JS Bin进行在线编写调试。 https://jsbin.com

一、Rxjs操作符

英文参考网址:https://www.learnrxjs.io/learn-rxjs/operators

中文参考网址:https://rxjs-cn.github.io/learn-rxjs-operators/operators/

二、Rxjs宝珠图状态流转

参考网址:https://rxmarbles.com/

1. from

可以把数组、Promise、以及Iterable 转化为 Observable。

  • 数组转换成Observable
1
2
3
4
5
6
// RxJS v6+
import { from } from 'rxjs';  
// 发射数组
const array$ = from([1, 2, 3]);  
// 输出: 1, 2, 3
array$.subscribe(val => console.log(val));
  • Promise转换成Ovservable
1
2
3
4
5
6
// RxJS v6+
import { from } from 'rxjs';
// 发射Promise
const promise$ = from(new Promise(resolve => resolve('Hello World!')));
// 输出: 'Hello World'
promise$.subscribe(val => console.log(val));

2. fromEvent

可以把事件event 转化为 Observable。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// html
// 可以尝试用 div>input#length生成
<div><input type="text" id="length"></div>

// RxJS v6+
import { fromEvent } from 'rxjs';
import { map } from 'rxjs/operators';

const length = document.getElementById('length');
const length$ = fromEvent(length, 'keyup');

// 输入框输入: '1234'
// 输出: '1','12','123','1234'
length$.subscribe(ev => console.log((ev.target as HTMLInputElement).value));

3. of

接受一系列的数据(可以是定义好的数据,并不一定是数组),转换成流,然后在emit出去。

1
2
3
4
5
6
7
// RxJS v6+
import { of } from 'rxjs';

// 发射values
const source$ = of({ name: 'Brian' }, [1, 2, 3]);
// 输出: {name: 'Brian'}, [1,2,3]
source$.subscribe(val => console.log(val));

4. interval

以一定的时间间隔发射一次

1
2
3
4
5
6
7
// RxJS v6+
import { interval } from 'rxjs';

// 1s发射一次
const source$ = interval(1000);
// 输出: 0,1,2,3,4,5...
source$.subscribe(val => console.log(val));

5. timer

一定时间之后启动一次就结束

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// RxJS v6+
import { timer } from 'rxjs';

// 1s启动一次就结束
const source$ = timer(1000);
// 输出: 0
source$.subscribe(val => console.log(val));

// 如果想要和interval类似的效果,可以利用timer第二个参数,在第一个参数执行完之后。
// 会按照第二个参数以一定时间间隔发射一次
// const source$ = timer(1000, 2000);