Rxjs takeWhile 和 filter 操作符的区别

import { of } from 'rxjs';
import { takeWhile, filter } from 'rxjs/operators';

// emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
const source$ = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);

// allow values until value from source equals 3, then complete
source$
  .pipe(takeWhile(it => it === 3))
  // log: 3, 3, 3
  .subscribe(val => console.log('takeWhile', val));

source$
  .pipe(filter(it => it === 3))
  // log: 3, 3, 3, 3, 3, 3, 3
  .subscribe(val => console.log('filter', val));

区别一目了然:

  • takeWhile, 当条件不满足时,Observable 设置为 completed 状态,停止 emit 值
  • filter, Observable 里所有满足条件的值都将被 emit
上一篇:Linux bashrc和profile的用途和区别


下一篇:java IO之 字符流 (字符流 = 字节流 + 编码表) 装饰器模式