【问题标题】:RxJS Subscribing varying amount of Observables inside SubscriptionRxJS 在 Subscription 中订阅不同数量的 Observable
【发布时间】:2020-09-08 14:15:28
【问题描述】:

在下面的代码 sn-p 中,我订阅了一个投资组合并遍历一个数组。对于数组的每个成员,我创建另一个订阅以收听其报价。

this.portfolio$
  .subscribe(portfolio) => {
    portfolio.watchlist.all.forEach((a) => {      
        this.store
          .select((s) => s.quotes.quotes[a._id])          
          .subscribe((q) => {
            console.warn('subscription')
          }
      }
    })
  })

是否有任何 RxJS 运算符可以让我摆脱外部订阅?最后,我只想拥有与数组中的引号一样多的订阅。

【问题讨论】:

    标签: javascript angular typescript rxjs ngrx


    【解决方案1】:

    是的,嵌套订阅是个坏主意,您可能会在这里造成非常严重的内存泄漏。

    尝试更像:

      this.portfolio$.pipe(
        switchMap(portfolio => {
          return combineLatest(portfolio.watchlist.all.map(
            a => this.store.select(s => s.quotes.quotes[a.id])
          ))
        })
      ).subscribe(combinedQ => console.log(combinedQ))
    

    在这里,您使用switchMap 切换到一个新流,这是combineLatest 中组合的所有可观察对象,它将发出数组中的所有最新值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 2017-10-10
      • 2018-10-15
      • 2021-07-26
      • 2016-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多