为什么takeWhile运算符不包含时进行过滤?

时间:2019-09-23 14:35:14

标签: typescript rxjs

我正在尝试使用包含选项设置为true的takewhile运算符,并且遇到一种我不理解的行为。 我已经能够隔离出一些代码,在这里我可以在其中重现行为

import { from, BehaviorSubject } from 'rxjs'; 
import { map, takeWhile } from 'rxjs/operators';

const value$ = new BehaviorSubject<number>(1);

const source = value$.pipe(
  map(x => `value\$ = ${x}`),
  takeWhile(x => !x.includes('4'), /*inclusive flag: */true)
);

source.subscribe(x => {
  console.log(x); 
  value$.next(4); // Strange behavior only in this case
  });

说明: 没有包含性标志,它将记录“ value $ = 1”,流完成

但是,将包含标志设置为true时,它会因stackoverflow异常而下降 enter image description here

我的问题是,为什么它会多次通过takeWh而不是在第一次出现后停止?

以下是长凳的链接,它有助于您理解: https://stackblitz.com/edit/rxjs-ag4aqx

1 个答案:

答案 0 :(得分:0)

在深入研究了运算符(https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/takeWhile.ts)的源代码之后,确实有一些错误要报告给github。

同时,这是一个固定的自定义takeWhileInclusive运算符

import { from, BehaviorSubject, Observable } from 'rxjs';
import { map, takeWhile } from 'rxjs/operators';

/** Custom takewhile inclusive Custom takewhile inclusive properly implemented */
const customTakeWhileInclusive = <T>(predicate: (value: T) => boolean) => (source: Observable<T>) => new Observable<T>(observer => {
  let lastMatch: T | undefined // fix
  return source.subscribe({
    next: e => {
      if (lastMatch) {
        observer.complete();
      }
      else {
        if (predicate(e)) {
          /*
           *   Code from https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/takeWhile.ts
           *  
           *   if (this.inclusive) {
           *      destination.next(value); // NO! with a synchronous scheduler, it will trigger another iteration without reaching the next "complete" statement 
           *      and there is no way to detect if a match already occured!
           *   }
           *   destination.complete();
           */

          // Fix:
          lastMatch = e; // prevents from having stackoverflow issue here
        }

        observer.next(e);
      }
    },
    error: (e) => observer.error(e),
    complete: () => observer.complete()
  });
});

const value$ = new BehaviorSubject<number>(1);

const source = value$.pipe(
  map(x => `value\$ = ${x}`),
  //takeWhile(x => !x.includes('4'), true)
  customTakeWhileInclusive(x => x.includes('4'))  // fix
);

source.subscribe(x => {
  console.log(x);
  value$.next(4);
});

实际运算符的问题在于,在同步调度程序上下文中,当匹配发生时,它将触发另一个迭代,并且永远不会达到“完成”状态。 正确的实现方式是标记匹配并执行另一个最后的迭代,在此迭代中您将完成对标记的检测。

链接到更新的堆栈闪电战:https://stackblitz.com/edit/rxjs-ag4aqx