RxJS 系列 – Mathematical and Aggregate Operators

前言

前几篇介绍过了 

Creation Operators

Filtering Operators

Join Creation Operators

Error Handling Operators

Transformation Operators

Join Operators

Utility Operators

Conditional and Boolean Operators

这篇继续介绍 Mathematical and Aggregate Operators

 

参考

Docs – Mathematical and Aggregate Operators

 

count

complete 以后, 统计之前总共发布了几次

const subject = new Subject<number>();
subject.pipe(count()).subscribe({
  next: v => console.log('next', v),
  complete: () => console.log('complete'),
});
subject.complete();

效果

如果一次都没有, 也会 next value 0 哦

 

max & min

complete 后, 找出之前发布过最大/最小的值

复制代码
const subject = new Subject<{ age: number }>();
subject.pipe(max(person => person.age)).subscribe({
  next: v => console.log('next', v),
  complete: () => console.log('complete'),
});
subject.next({ age: 50 });
subject.next({ age: 72 });
subject.next({ age: 40 });
subject.complete();
复制代码

效果

 

这里我只给 max 的例子, min 就是找最小.

 

reduce

reduce = scan + last

在 complete 之后, 它才去跑 JS 的 Array.reduce

const subject = new Subject<number>();
subject.pipe(reduce((acc, value) => acc + value, 0)).subscribe(v => console.log('next', v));
subject.next(1);
subject.next(2);
subject.next(3);
subject.complete();

效果

用 scan + last 来实现

.pipe(
  scan((acc, value) => acc + value, 0),
  last()
)

 

一句话总结

count : complete 后统计之前总共发布几次

max & min : complete 后, 找出之前发布过最大/最小值

reduce : 等价于 scan + last. scan 每一次都会发布, reduce 只在 complete 后才发布.

 

posted @   兴杰  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
历史上的今天:
2021-04-03 Google Analytics & Ads 学习笔记 2 (GA4 版本)
点击右上角即可分享
微信分享提示