caker
caker

Reputation: 178

Getting observable values in order when looping?

I'm having a difficult time figuring out how to print users in order using Observables. Right now this will print out of order depending on when the requests are resolved. How do I get it to print in order?

printUsersInOrder() {
  for (var i = 0; i < 10; i++) {
    this.getUser(i)
  }
}

// kibanaService uses angular2/http
getUser(userId: int) {
  this.kibanaService.getUser(userId).subscribe(
    res => {
      console.log(userId)
      console.log(res)
    },
    err => {
      console.log(err);
    }
  }
);

Upvotes: 1

Views: 221

Answers (1)

Karlen
Karlen

Reputation: 1394

You can use combineLatest RxJs stream.

  printUsersInOrder() {
    let requests = [];
    let successfulResponses = []; // <-- Let's keep track of successful responses
    for (var i = 0; i < 10; i++) {
      requests.push(this.getUser(i).do(res => successfulResponses.push(res)))
    }

    Observable.combineLatest(requests)
    .subscribe((responses)=>{
        // response array will have the same order as it is in the requests array
        responses.map(res => console.log(res))
    }, (err) => {
        console.log(successfulResponses) // <--- This will print all successful responses
        console.log(err)
    })
  }

  // kibanaService uses angular2/http
  getUser(userId: int) {
    this.kibanaService.getUser(userId)
  }

For more about combineLatest you can find here and here.

Upvotes: 2

Related Questions