RxJS skipWhile vs filter

时间:2018-03-22 07:59:50

标签: javascript rxjs

skipWhile和过滤器运算符之间有什么区别?

const source = interval(1000);
const example = source.pipe(skipWhile(val => val < 5));
const subscribe = example.subscribe(val => console.log(val));


const source = interval(1000);
const example = source.pipe(filter(val => val > 5));
const subscribe = example.subscribe(val => console.log(val));

3 个答案:

答案 0 :(得分:16)

不同之处在于,在表达式评估为false时,skipWhile会切换到镜像其源可观察性 - 因此它将停止过滤掉任何其他值。

例如:

Observable.from([1,2,3,4,5])
  .pipe(filter(val => val % 2 == 0)) // filters out odd numbers
  .subscribe(val => console.log(val)); // emits 2,4

Observable.from([1,2,3,4,5])
  .pipe(skipWhile(val => val % 2 == 1)) // filters odd numbers until an even number comes along
  .subscribe(val => console.log(val)); // emits 2,3,4,5

答案 1 :(得分:2)

Observable.from(["Citizen 1","Citizen 2","President","Citizen 3","Citizen 4"])
  .pipe(filter(val => val == "President")) // Allow in a bunker only a president
  .subscribe(val => console.log(val)); // emits President

Observable.from(["Citizen 1","Citizen 2","President", "Citizen 3","Citizen 4"])
  .pipe(skipWhile(val => val != "President")) // Allow citizens in a bunker after a president has entered and is safe.
  .subscribe(val => console.log(val)); // emits President, Citizen 3, Citizen 4

答案 2 :(得分:1)

skipWhile操作员将忽略排放,直到指定条件变为假为止,但是此后,它将继续从可观察的来源中继续获取值。

const randomNumbersLessThanEqualToTen = interval(1000).pipe(map((num) => {
    const randomNumber = Math.floor(Math.random()*num);
    console.log('Random Number Generated', randomNumber);
    return randomNumber;
}), skipWhile(num => num < 10));

randomNumbersLessThanEqualToTen.subscribe((number) => {
    console.log('Number not skipped', number);
});

o / p

Random Number Generated 6
Random Number Generated 0
Random Number Generated 5
Random Number Generated 0
Random Number Generated 5
Random Number Generated 11
Number not skipped 11
Random Number Generated 6

一旦生成并发出11(即num <10 === false),所有生成的数字都会被记录并打印。

以下是filter的示例:

const randomNumbers = interval(1000).pipe(map((num) => {
    const randomNumber = Math.floor(Math.random() * num);
    console.log('Random Number Generated', randomNumber);
    return randomNumber;
}), filter(num => num > 10));
randomNumbers.subscribe((number) => {
    console.log('Number is greater than 10 -->', number);
});

o / p

Random Number Generated 7
Random Number Generated 11
Number is greater than 10 --> 11
Random Number Generated 13
Number is greater than 10 --> 13
Random Number Generated 13
Number is greater than 10 --> 13
Random Number Generated 3
Random Number Generated 2

因此,上面的输出仅展示了该过滤器仅根据指定的条件对排放进行过滤,并且在整个可观察寿命内对其进行过滤。