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

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

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>:

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

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?

>Solution :

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

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