switchMap,startWith,switchMap?

时间:2018-09-07 01:38:15

标签: typescript rxjs

this.timeline$ = app.selectedSites$.pipe(
  debounceTime(2000),
  switchMap(sites => this.interval.pipe(map(() => sites))),
  switchMap(sites =>
    analytics.timeline(sites, 60 * 24 * 2, 60).pipe(
      map(result => {
        const colors = getColors(result);

        return {
          labels: result[0].datapoints.map(pair => pair[1]),
          datasets: (<any[]>result).map((target, i) => ({
            pointRadius: 0,
            label: target.target,
            fill: false,
            backgroundColor: colors[i % colors.length],
            borderColor: colors[i % colors.length],
            data: target.datapoints.map(pair => ({
              y: pair[0],
              x: pair[1]
            }))
          }))
        };
      })
    )
  ),
  share()
);

我希望this.timeline $在selectedSites $更改(已去抖动)时发出null,并开始为新列表加载第一个数据,然后每30秒刷新一次,但刷新前不发出null。 ..我不知道将startWith(null)放在哪里...

2 个答案:

答案 0 :(得分:1)

换句话说,您需要两个流:首先是所有运算符,另一个是发出null的流。

const source$ = app.selectedSites$
  .pipe(
    debounceTime(2000)
  )


this.timeline$ = source$.pipe(
  switchMap(sites => this.interval.pipe(map(() => sites))),
  switchMap(sites =>
    analytics.timeline(sites, 60 * 24 * 2, 60)
      .pipe(
        map(result => getField(result))
      )
  ),
  merge(source$.pipe(mapTo(null))),
  share()
);

答案 1 :(得分:0)

这就是我最终得到的...

toChartData(selector: (sites: string[]) => Observable<any>) {
    return this.app.selectedSites$.pipe(
      debounceTime(2000),
      switchMap(sites =>
        this.interval.pipe(
          switchMap(() => selector(sites)),
          startWith(null)
        )
      ),
      share()
    );
}