Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wait for subscription in the same function

I would like to know how I can wait in an If-Else-branch for all REST-calls to finish, even though the Else-side has no REST calls.

Here’s an example:

createNewList(oldList: any[]) {
 const newList = [];
 oldList.forEach(element => {
   if (element.isAwesome) {
     this.RESTCall().subscribe(result => {
       element.property = result;
       newList.push(element);
     });
   } else {
    newList.push(element);
   }
 });

 // wait here for all elements of RESTCall, then:
 return newList;
}

I hope you can follow me.
In the current version, of course, the restcalls take much longer and the function transfers the list too early.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My first approach would be to add different, higher-level observables to a list, merge them via mergeAll (https://www.learnrxjs.io/learn-rxjs/operators/combination/mergeall) and then execute this complete() function. But that seems very tortuous to me.

Do you have any tips or processes for me to solve something like this in an easier way?

>Solution :

You can turn your list into a list of observables instead, this will make it easier to reason about.

const tasks = oldList.map(element =>
  element.isAwesome ? performRestCall(element) : of(element));

performRestCall(element: any): Observable<any> {
  return this.RESTCall().pipe(
    map(result => {
      element.property = result;
      return element;
    })
  );
}

Then you can use forkJoin to get all the results:

forkJoin(tasks).subscribe(newList => {
  console.log(newList);
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading