Skip to content

AHABHGK

辅助类数据流

数学类操作符

这些操作符必定会遍历上游 Observable 对象中吐出的所有数据才给下游传递数据,也就是说,它们只有在上游完结的时候,才给下游传递唯一数据

count 统计数据个数

1interval(1000).pipe(count()) == never()
1timer(1000).pipe(
2 concat(timer(1000)),
3 count(),
4) // log 2 after 2 secends
5
6const numbers = range(1, 7);
7const result = numbers.pipe(count(i => i % 2 === 1))
8result.subscribe(x => console.log(x)) // 4

max、min

1interface Person {
2 age: number,
3 name: string
4}
5of<Person>(
6 {age: 7, name: 'Foo'},
7 {age: 5, name: 'Bar'},
8 {age: 9, name: 'Beer'},
9).pipe(
10 max<Person>((a: Person, b: Person) => a.age < b.age ? -1 : 1),
11).subscribe((x: Person) => console.log(x.name)) // -> 'Beer'

reduce 规约

1const clicksInFiveSeconds = fromEvent(document, 'click').pipe(
2 takeUntil(interval(5000)),
3)
4const ones = clicksInFiveSeconds.pipe(mapTo(1))
5const count = ones.pipe(reduce((acc, one) => acc + one, 0))
6count.subscribe(x => console.log(x))

条件布尔类操作符

every

find、findIndex

isEmpty

1import { EMPTY } from 'rxjs'
2import { isEmpty } from 'rxjs/operators'
3
4const result = EMPTY.pipe(isEmpty())
5// true
6Observable.create((ob) => sleep(1000).then(() => ob.complete())).pipe(isEmpty())
7// true after 1000 ms

defaultIfEmpty

接受一个参数做默认值,如果上游空的话会返回一个默认值给下游,没有没传默认值则为 null

1const clicks = fromEvent(document, 'click')
2const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)))
3const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'))
4result.subscribe(x => console.log(x))