RxJS Subscribing varying amount of Observables inside Subscription Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of RxJS Subscribing varying amount of Observables inside Subscription without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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.

We are here to answer your question about RxJS Subscribing varying amount of Observables inside Subscription - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji