Home > Enterprise >  wait for two subscribe to finish without nesting
wait for two subscribe to finish without nesting

Time:09-02

This works but it's very nested, is there a way to do this without the nesting? Like run console.log('both API calls are finished!') after all API calls are finished but for any number of API calls

this.service.apiCallOne().subscribe((res) => {
  this.service.apiCallTwo().subscribe((res) => {
    console.log('both API calls are finished!')
  })
})

api calls are not reliant on each other either, so it doesn't matter which order they finish, I just want to know when they are both finished

CodePudding user response:

You're searching for forkJoin:

forkJoin([this.service.apiCallOne(), this.service.apiCallTwo()])
.subscribe(([resOne, resTwo]) => {
  // this will trigger only when both calls complete.
  // please pay attention to error management, which can be tricky!
});

  • Related