Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to work with dynamic argument (urls) in Observable.forkJoin()

Tags:

angular

rxjs

SO I love forkJoin, basically the replacement of Promise.all, but I can't figure how to feed it a dynamic list as in:

Observable.forkJoin(
        this.http.get('/app/books.json').map((res:Response) => res.json()),
        this.http.get('/app/movies.json').map((res:Response) => res.json())
    ).subscribe(
      data => {
        this.books = data[0]
        this.movies = data[1]
      },
      err => console.error(err)
    );

only that I need to create the http.gets at runtime (the URLs will be different, destinations and total URLs generated all will be dynamic), tried to pass a config object but it didn't like it...

tx for reading,

Sean.

like image 495
born2net Avatar asked Feb 07 '23 07:02

born2net


2 Answers

forkJoin takes first argument as

args (Arguments | Array): An array or arguments of Observable sequences or Promises to collect the last elements for.

So, you can simply pass it an array of observables . Here is a plunker

let observables = [
  this.http.get('/app/books.json').map((res:Response) => res.json()),
  this.http.get('/app/movies.json').map((res:Response) => res.json())
];

Observable.forkJoin(observables).subscribe(
   data => {
        this.books = data[0]
        this.movies = data[1]
   },
   err => console.error(err)
);
like image 72
Abdulrahman Alsoghayer Avatar answered Feb 09 '23 22:02

Abdulrahman Alsoghayer


I landed here looking for a way to identify the results of a dynamically assembled group of observables. If I pass an array of observables, I can't know which result will be at which index because the number of and order of observables in the array is unknown.

Since RxJS 6.5+, you can pass an object instead of an array into ForkJoin, where the key will identify the observable, and the value of the key is the observable (known as a dictionary).

// use some logic to dynamically assemble dictionary
const dictionary = {};

if (shouldGetBooks) {
   dictionary.books = this.http.get("/app/books.json");
}
if (shouldGetMovies) {
   dictionary.movies = this.http.get("/app/movies.json");
}

forkJoin(dictionary).subscribe((results) => {
   console.log(results); // { books: booksJson, movies: moviesJson }
});

Now the results are easily identifiable by key.

like image 25
Wesley Avatar answered Feb 09 '23 21:02

Wesley