适用操作符 功能需求
count 统计数据流中产生的所有个数
max、min 获得数据流中最大最小的数据
reduce 对数据流中所有数据进行规约操作
every 判断是否所有数据满足某个判定条件
find、findIndex 找到第一个满足判定条件的数据
isEmpty 判断一个数据流是否不包含任何数据
defaultIfEmpty 如果一个数据流为空就默认产生一个指定数据

count: 统计数据个数

1
2
3
4
const source$ = timer(1000).pipe(
concat(timer(1000))
)
source$.pipe(count())

00
2
值得注意的是count$只有在2秒钟之后才产生这个数据2

max和min: 最大最小值

max,min 的输入可以是纯数值

1
of(2,7,6,6,8,1).pipe(min())

1
也可以输入一个比较函数

1
2
3
4
5
6
7
8
of(
{name: 'Jack', age: 20},
{name: 'Mike', age: 10},
{name: 'David', age: 30}
).pipe(
max((a,b) => a.age - b.age),
map(item => item.name)
)

David

reduce: 规约统计

如果需要对上游Observable吐出的数据进行更加复杂的统计运算,就可以使用reduce

1
2
3
4
range(1,20).pipe(
reduce((acc, current) => acc + current,
0)
)

210

every

every属于条件布尔类操作符,其输出结果为一个而且唯一的布尔值

1
of(2,3,4,5).pipe(every(x => x > 0))

true

find

1
of(7,7,7,6,5,3).pipe(find(x => x %2 === 0))

6

isEmpty

用于检测上游Observable对象是否为”空”
“空” = 没有吐出任何数据就完结的Observable对象

1
interval(1000).pipe(isEmpty())

false

1
empty().pipe(isEmpty())

true

defaultIfEmpty

1
empty().pipe(defaultIfEmpty('not empty'))

not empty