2

What is the RxJs equivalent of Promise.all() whereby the then block only executes when all promises are resolved?

const request1 = this.http.get('/api/hello').toPromise() // returns a promise
const request2 = this.http.get('/api/there').toPromise() // returns a promise

Promise.all([request1, request2]).then(([response1, response2]) => {
  // executes if/when ALL the promises resolve
  console.log('response1', response1);
  console.log('response2', response2);
}).catch(err => {
  // executes if ANY ONE of the promises fail / reject
  console.log('err', err);
})

So what is the equivalent approach in RxJs? thanks

danday74
  • 52,471
  • 49
  • 232
  • 283
  • 2
    Possible duplicate of [Promise.all behavior with RxJS Observables?](https://stackoverflow.com/questions/35608025/promise-all-behavior-with-rxjs-observables) – Jeto Oct 18 '18 at 20:48
  • 1
    [`forkJoin`](https://www.learnrxjs.io/operators/combination/forkjoin.html) – Pankaj Parkar Oct 18 '18 at 20:49

1 Answers1

12

You can use forkJoin

This operator is best used when you have a group of observables and only care about the final emitted value of each. You can use this operator to issue multiple requests.

import { forkJoin, Observable } from "rxjs";

Usage

const request1 = this.http.get('/api/hello'); //return an observable
const request2 = this.http.get('/api/there') //return an observable

forkJoin([request1,request2]).subscribe((response)=>{

    //after all the successful requests 
    //response.forEach((eachRes)=>{console.log(eachRes)});
    //or response[0] , response[1]


});
Jameel Moideen
  • 7,542
  • 12
  • 51
  • 79