过滤操作符
1. filter¶
通过给定的条件,把值过滤出来之后,发射出去。
1 2 3 4 5 6 7 8 9 10 11 | // RxJS v6+ import { from } from 'rxjs'; import { filter } from 'rxjs/operators'; // 发射(1,2,3,4,5) const source$ = from([1, 2, 3, 4, 5]); const new$ = source.pipe(filter(num => num % 2 === 0)); // 输出: '2', '4' new$.subscribe(val => console.log(val)); |
数据流图例:

2. take¶
取得流里面前几个值。
1 2 3 4 5 6 7 8 9 | // RxJS v6+ import { of } from 'rxjs'; import { take } from 'rxjs/operators'; const target$ = of(1, 2, 3, 4, 5); // 取两个值 const new$ = target$.pipe(take(2)); // 输出: '1', '2' new$.subscribe(val => console.log(val)); |
数据流图例:

3. first/last¶
取得第一个和最后一个值
4. skip¶
跳过源得前n个再发射。
1 2 3 4 5 | // 1. 第一种写法 skip(n) // 2. 第二种写法 filter(val, index) => index > n |
5. debounce¶
根据一个选择器函数,舍弃掉在两次输出之间小于指定时间的发出值(避免每一次得请求都触发, 相当于一个滤波器)。
1 2 3 4 5 6 7 8 9 10 11 | // RxJS v6+ import { of, timer } from 'rxjs'; import { debounce } from 'rxjs/operators'; // 瞬间发出3个字符串 const source$ = of('1', '2', '3'); const debounce$ = source$.pipe(debounce(() => timer(1000))); // 输出:'3' debounce$.subscribe(val => console.log(val)); |
6. debounceTime¶
舍弃掉在两次输出之间小于指定时间的发出值。(此操作符在诸如预先知道用户的输入频率的场景下很受欢迎!)
1 2 3 4 5 6 7 | ... const length$ = fromEvent(length, 'keyup').pipe(pluck('target', 'value')); // 在两次键盘敲击之间等待0.5秒方才发出当前值 // 并丢弃这0.5秒内的所有其他值 const new$ = length$.pipe(debounceTime(500)); ... |
数据流图例:

7. distinct¶
过滤掉重复元素。
数据流图例:

8. distinctUntilChanged¶
如果下一个元素和前一个相同就舍弃掉。
数据流图例:
