【问题标题】:RxJS operators execution orderRxJS 操作符执行顺序
【发布时间】:2020-02-26 07:19:52
【问题描述】:

考虑到我有以下代码:

private readonly postAction$ = new Subject();

postStream$ = this.postAction$.pipe(
    exhaustMap(() => {
      this.count ++;
      console.log('fired')
      return of('my other post');
    }),
    startWith(''),
    exhaustMap(()=> {
      this.count ++;
      console.log('fired first')
      return of('my post' + this.count);
    })
  )

我使用async 管道在我的模板中订阅。

我没想到这会起作用,但控制台的输出是:

> fired first

在我对 postAction$ 主题调用 .next() 之前,永远不会调用第一个 console.log('fired')

RxJS 操作符的执行上下文是什么?它们是如何工作的?我原以为第一个排气图需要在运行其余运算符之前发出一个值。在 rxjs 中找不到任何东西 docs

stackblitz上的演示

【问题讨论】:

    标签: angular rxjs rxjs-pipeable-operators


    【解决方案1】:

    我认为找到答案的最佳方法是实际了解幕后发生的事情(我还没有这样做,但我希望将来这样做)。

    在那之前,我是这样看待事物的。

    想象成河流
    穿过河流,这些船基本上是发出的值
    还有桥梁,您可以将它们视为运营商。每座桥都可能需要一些条件来决定哪条船可以继续前进,哪条不能。

    我是这样想象的:

                The value from `startWith`
                         ↓
    ~~~~~~~~|~~~~~~~~|~~~B~~~~|~~~~~~~~
    
            ^        ^        ^
            |        |    `exhaustMap(() => {})`
            |        |
            |   `startWith('B')`
            |
    `exhaustMap(() => {})`
    

    async 管道在内部订阅(和取消订阅)给定的 observable。我认为订阅是建立河流桥梁的过程。还没有船。
    但是,在这种情况下,可以从第二座桥出发,这意味着第一个桥对此无话可说。

    这个,如果你这样放置桥梁:

     postStream$ = this.postAction$.pipe(
        startWith(''),
        exhaustMap(() => {
          this.count ++;
          console.log('fired')
          return of('my other post');
        }),
        exhaustMap(()=> {
          this.count ++;
          console.log('fired first')
          return of('my post' + this.count);
        })
      )
    

    您应该在控制台中看到以下输出:

    fired
    fired first
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 2021-07-12
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多