【问题标题】:Combination of reduce and scan with a subject结合减少和扫描与主题
【发布时间】:2017-11-11 01:22:17
【问题描述】:

RxJS 版本:5.5.2

我有一个数组const v = [1, 2, 3];

我希望能够从这个数组创建一个 Subject 并像一个 Observable 一样工作,直到它消耗 1、2、3 值。之后我想表现得像个主题。

这就是我遇到麻烦的地方。我需要在初始值 v = [1, 2, 3] 上使用 reduce 然后每次主题添加另一个值以使用 scan

代码如下:

const v = [1, 2, 3];
const sub = new Subject<number>();
const observable = sub.pipe(
  startWith(0),
  concatMap(x => from(v)),
  scan((a, b) => { // or reduce
    return a + b;
  }, 0),
);
observable.subscribe(x => console.log(x));

如果我在这里使用scan,则会在控制台上打印

1
3
6

我想要打印的只是最后一个值6。将 scan 替换为 reduce 将仅在主题完成后才能完成工作(这样我以后就不能再发送任何值了)。

然后主题每次发送一个值sub.next(4);打印10等等。

【问题讨论】:

    标签: typescript rxjs rxjs5


    【解决方案1】:

    您可以使用skipWhile() 跳过您不想要的来自scan 的前 N ​​个发射:

    import { Subject } from "rxjs/Subject";
    import { from } from "rxjs/observable/from";
    import { of } from "rxjs/observable/of";
    import { merge, concatMap, scan, skipWhile, tap } from "rxjs/operators";
    
    const v = [1, 2, 3];
    let skipFirst;
    
    const sub = new Subject<number>();
    
    const observable = of(v).pipe(
      tap(arr => skipFirst = arr.length),
      concatMap(arr => from(arr)),
      merge(sub),
      scan((a, b) => { // or reduce
        return a + b;
      }, 0),
      skipWhile(() => --skipFirst > 0),
    );
    observable.subscribe(x => console.log(x));
    
    sub.next(5);
    

    打印出来:

    6
    11
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多