Tobias S.
Tobias S.

Reputation: 23905

RxJS Subscribing varying amount of Observables inside Subscription

In the following code snippet I subscribe to a portfolio and iterate through an array. For each member of the array I create another subscription to listen to its quotes.

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

Is there any RxJS operator which allows me to get rid of the outer subscription? In the end I only want to have as many subscriptions as I have quotes in the array.

Upvotes: 2

Views: 91

Answers (1)

bryan60
bryan60

Reputation: 29355

yea nesting subscribes is a bad idea and you're probably creating a pretty severe memory leak here.

try more like:

  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))

here you use switchMap to switch into a new stream, which is all of the observables combined in combineLatest which will emit all latest values in an array.

Upvotes: 6

Related Questions