Parallel RXJS Observables

Run request to two or more http or similar endpoints that come back as observables, having their results merged into a single observable.

Published: 6/7/2024
getForms(): Observable<JsonFormSchema[]> {
  return forkJoin({
    form1: forkJoin({
      controls: this.http.get<JsonFormControlSchema>('/assets/fs1.json'),
      ui: this.http.get<JsonFormUISchema>('/assets/fs1-ui.json'),
    }).pipe(
      map((result) => ({
        id: '1',
        title: 'Demo',
        ...result,
      }))
    ),
    form2: forkJoin({
      controls: this.http.get<JsonFormControlSchema>('/assets/fs2.json'),
      ui: this.http.get<JsonFormUISchema>('/assets/fs2-ui.json'),
    }).pipe(
      map((result) => ({
        id: '2',
        title: 'Test and tag',
        ...result,
      }))
    ),
  }).pipe(map((forms) => [forms.form1, forms.form2]));
}
  • forkJoin first merges the results from to request for .json files, then merges again the results of multiples of these
  • map on each inner request is used to add additional fields
  • map on the outer request is used build to the specified type