Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure observables in for loop are all finished before executing other code

Tags:

angular

rxjs

I have a piece of code that looks like this:

getPersons().subscribe(
    persons => {
        for (const person of persons) {
            getAddress(person.id).subscribe(
                address => {
                    person.address = address;
                }
            );
        }
        doSomethingWithAddresses();
     }
);

The problem is that doSomethingWithAddresses is executed before all the getAddress observables are finished. How can you make sure they are all finished before executing subsequent code?

like image 708
Spacejockey Avatar asked Sep 01 '25 04:09

Spacejockey


1 Answers

You should make use of RxJS's forkJoin to wait for the for..of loop to be completed before returning all the observables.

Here are the changes you should make to your code:

getPersons().subscribe(
  persons => {
    const observablesList = [];
    for (const person of persons) {
      const getAddressObservable = getAddress(person.id);
      observablesList.push(getAddressObservable)
    }
    forkJoin(observablesList).subscribe(response => {
      // console.log(response) to check that there is a list of returned observables
      const result = persons.map((person, index) => {
        person['address'] = response[index]['address'];
        return person;
      })
      doSomethingWithAddresses();
    })
  }
);

Alternatively, you may try this to prevent the chaining of subscribe()

getPersons().pipe(
  mergeMap(persons => {
    const observablesList = [];
    for (const person of persons) {
      const getAddressObservable = getAddress(person.id);
      observablesList.push(getAddressObservable)
    }
    return observablesList;
  })
).subscribe(response => {
  // console.log(response) to check that there is a list of returned observables
  const result = persons.map((person, index) => {
    person['address'] = response[index]['address'];
    return person;
  })
  doSomethingWithAddresses();
})
like image 66
wentjun Avatar answered Sep 02 '25 17:09

wentjun