Da Mike
Da Mike

Reputation: 463

RxJS: Subscribe to multiple independent observables and notify when all are done

Before my page is rendered, I want to fetch data from 5 independent different APIs (there is no need to wait for the first in order to fetch the data from the second), and once all of them are complete, I want a boolean variable to be set. Something like this

http.get(url1).subscribe(response => {
  // set response data 
  // & somehow notify that this call is complete?
});

http.get(url2).subscribe(response => {
  // set response data
  // & somehow notify that this call is complete?
});

...

How can I achieve that with Angular and RxJS?

Upvotes: 0

Views: 109

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27471

You can use forkJoin to combine all api call's. Finally use tap operator on individual obseravble to get response independently

  const all = forkJoin([
    http.get(url2).pipe(
      tap((res)=>{
         // set response data 
      })
    ),
    http.get(url2).pipe(
      tap((res)=>{
         // set response data 
      })
    )    
  ]).subscribe(()=>{
   // &  notify after all api call is complete.
  })

Upvotes: 1

Eli Porush
Eli Porush

Reputation: 1567

simply use forkJoin :

forkJoin([http.get(url1), http.get(url2)]).subscribe(dataAsArray => {
   // do what you need with the data
})

Upvotes: 3

Related Questions