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.
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?
CodePudding user response:
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);
})