【问题标题】:.first() operator affects other subscriptions.first() 运算符影响其他订阅
【发布时间】:2017-03-08 19:05:28
【问题描述】:

示例代码:

const test1$ = Rx.Observable.interval(1000)
const test2$ = Rx.Observable.interval(1000)

// This subscription need to get every value continuously
const firstSub = test2$
  .do(val => console.log('Service: ', val))
  .subscribe()

// This subscription need to get only first value and stop
const secondSub = Rx.Observable.combineLatest(test1$, test2$)
  .do(val => console.log('Method: ', val))
  .first()
  .subscribe()
  • 首次订阅在应用启动后立即开始。
  • 第二次订阅由点击事件开始(因此它可以运行几次)。

当我使用 .first().take(1) 运算符时,不知何故,第一次订阅也会受到它的影响,并停止获取值。

如何更改该行为以仍然从第一个订阅中获取值,而仅从第二个订阅中获取一个值并停止?

【问题讨论】:

    标签: javascript rxjs rxjs5


    【解决方案1】:

    当您将空 (undefined) 与 subscribe() 一起使用时,库中当前存在错误。

    正在通过以下方式解决此问题: https://github.com/ReactiveX/rxjs/pull/2238

    与此同时,如果您像这样更新代码,一切都会按预期进行。

    const test1$ = Rx.Observable.interval(1000)
    const test2$ = Rx.Observable.interval(1000)
    
    // This subscription need to get every value continuously
    const firstSub = test2$
      .do(val => console.log('Service: ', val))
      .subscribe({})
    
    // This subscription need to get only first value and stop
    const secondSub = Rx.Observable.combineLatest(test1$, test2$)
      .do(val => console.log('Method: ', val))
      .first()
      .subscribe({})
    

    【讨论】:

    • 谢谢。这就解释了奇怪的 Rx 行为。
    【解决方案2】:

    看起来使用不带任何回调的 .subscribe() 会改变 .first() 运算符的行为。

    如果我在.subscribe() 方法中传递任何next 回调,.first() 运算符将正常工作。

    比如在secondSub

    .subscribe()
    

    .subscribe(test => console.log('Method: ', test))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2012-12-17
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多