【问题标题】:Select operator based on stream value根据流值选择算子
【发布时间】:2021-05-17 16:54:14
【问题描述】:

有一个数据源发出值 0 或 1。

如果为 0,我想通过 switchMap 运算符进行管道传输。

如果 1 我想通过排气映射操作符进行管道传输。

我该怎么做?

https://stackblitz.com/edit/rxjs-gcvsfe

const source = from([0, 0, 0, 1, 1, 1]).pipe(
  // if value === 0
  switchMap(value => {
    return of("Operator switchMap, value: " + value);
  })
  // if value === 1
  // exhaustMap(value => {
  //   return of('Operator exhaustMap, value: ' + value)
  // })
);

source.subscribe(console.log);

【问题讨论】:

    标签: rxjs


    【解决方案1】:

    如果您想切换运营商,那么您可能希望拥有 2 个不同的流。

    如果是这种情况,那么您可以使用filter 运算符并拥有类似的东西

    const source = from([0, 0, 0, 1, 1, 1]);
    
    const stream_0 = source.pipe(
      filter(val => val === 0),
      switchMap(value => {
        return of("Operator switchMap, value: " + value);
      })
    )
    const stream_1 = source.pipe(
      filter(val => val === 1),
      exhaustMap(value => {
         return of('Operator exhaustMap, value: ' + value)
      })
    );
    
    merge(stream_0, stream_1).subscribe(console.log);
    

    【讨论】:

      【解决方案2】:

      我最终得到了这个(exhaustMap 在自定义操作符 paginateList 中)

      this._baseSubject = new Subject<ListPaged>();
      this._nextPageSubject = new Subject<ListPaged>();
      
      this._items$ = this._baseSubject.pipe(
        switchMap((req) => {
          return this._nextPageSubject.pipe(
            startWith(req),
            paginateList(paginate)
          );
        })
      );
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-29
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多