都2022了 我rxjs还是不熟!!! -- 缓慢更新中

252 阅读1分钟

个人理解的rxjs

我个人认为rxjs就是接收消息并对消息进行处理(这里的消息可以是多个)再返回给他的订阅者

比如:你网上购物并下单(Observable(可观察的物件)) 平台对你的订单进行处理(Operators(运算符))并将处理完的信息发送给用户和商家(Observer者物件(观察者)) 后续订单状态还有更新的话 继续发送给此订单的订阅者(这一串流程表示为Subscription) 官网详细介绍

创建Observables并发送的几种常用方式

new Observable. 最常见的是,observables 是使用创建函数创建的,例如offrominterval等 详细见官网

const observable = new Observable((subscriber) => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  setTimeout(() => {
    subscriber.next(4);
    subscriber.complete();
  }, 1000);
});
const observable2 = of(1,2,3,4);
const observable3 = from([1,2,3,4]);

订阅Observables

observable.subscribe((res) => {
  console.log(res);
}, (err) => {
  console.log('这里是错误情况', err);
}, () => {
  console.log('这里是complete情况');
});
observable2.subscribe((res) => {
  console.log('of-' + res);
});
observable3.subscribe((res) => {
  console.log('from-' + res);
});

输出结果

开始订阅 1 2 3 of-1 of-2 of-3 of-4 from-1 from-2 from-3 from-4 结束订阅 4 done

如何取消订阅呢

observable.unsubscribe();
observable2.unsubscribe();
observable3.unsubscribe();

如何对Observable进行处理-Operators

有以下两种运算符1.Pipeable Operators 2.Creation Operators

Pipeable Operators顾名思义管道运算符 在管道中对数据进行处理并最后由管道发送处理 这里可以多个运算符同步执行

of(1, 2, 3)
.pipe(filter((x) => x > 1),map((x) => x * x))
.subscribe((v) => console.log(`value: ${v}`));

// 打印结果如下:
// value: 4
// value: 9
fromEvent(document'click')
.pipe(concatMap(() => fromEvent(document'mouseenter')))
.subscribe(() => {
    // 只有click之后才能触发mouseenter事件
});
// 常用运算符示例

常用的管道运算符

Image.png

Image.png

Creation Operators顾名思义创建运算符 接收非 Observable 参数,比如数字,然后创建一个新的 Observable,而不是将一个输入 Observable 转换为输出 Observable。

of(1, 2, 3)
.pipe(filter((x) => x > 1),map((x) => x * x))
.subscribe((v) => console.log(`value: ${v}`));

// 打印结果如下:
// value: 4
// value: 9

常用的创建运算符

Image.png