dirtyw0lf
dirtyw0lf

Reputation: 1958

Waiting for subscribe for loop to end before continuing

How to check if the following for loop is completed in pushing all results to nodesToExpand?

getFilterResult is an http request call in the nodeService service.

  for(var step in paths)
  {
    this.nodeService.getFilterResult(paths[step]).subscribe(
      (node) =>
      {
        nodesToExpand.push(node);
      }
    );
  }

Upvotes: 0

Views: 474

Answers (1)

CaKa
CaKa

Reputation: 3779

What you are currently doing looks very wrong to me. Try not to mix RxJS with for loops. Usually, RxJS has something that fulfills your need, take a look at https://rxmarbles.com/.

If you want to wait for multiple streams until they emit an event, you'd go with combineLatest(). It not only tells you when all http requests responded, but also hands you over the data in a tuple structure.

const httpCalls:Array<Observable<any>> = paths.map(step => this.nodeService.getFilterResult(step));
combineLatest(HttpCalls)
.subscribe(results => console.log(results));
// --> [Call1Result, Call2Result, ...]

Upvotes: 3

Related Questions