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 @ 2023-04-03 21:52  兴杰  阅读(42)  评论(0编辑  收藏  举报