Home > Enterprise >  Build and execute a dynamic list of observables with variables with Typescript and Angular
Build and execute a dynamic list of observables with variables with Typescript and Angular

Time:06-08

I am receiving an array that has 1..N number of userIds. I am building a unique list of those Ids so that I only query the user info once:

const uniqueUserIds = [
  ...new Set(requests.map((item) => Number(item.userId))),
];

With this list of unique user Ids, I'd like to build a task list to go out and get each of them before moving on to the next block of code.

var tasks: Observable<User>[] = [];
uniqueUserIds.map((userId) => {
  tasks.push(this.getUserInfo(userId));
});

The getUserInfo method just returns an Observable<User>:

getUserInfo(userId: number) {
  return this.userServiceHttpClient.getUser(userId);
}

I've tried using the following, but none of my Observables are executing:

Promise.all(tasks).then((value) => {
  console.warn(value);
});

If I take the value and do a .subscribe, then the observable is executed. Isn't there a way to take a list of Observables, all returning the same type, concatenate the results into an array, and then continue execution?

CodePudding user response:

You can't use Promise.all() to await an array of Observables since it only works with Promises.

The forkJoin operator from RxJS was made exactly for this scenario :)

import { forkJoin } from "rxjs";

forkJoin(
  uniqueUserIds.map(id => this.getUserInfo(id))
).subscribe(value => {
  console.log(value)
})

Sandbox

  • Related