Subscribing to Multiple Observables

JS
S
JavaScript

Simple example of how to subscribe to 2 multiple observables (in this case they are API calls on Angular 7)

1import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
2import { combineLatest } from 'rxjs';
3
4// ...
5
6    const updateResults$ = combineLatest(
7      this.apiService.updateTask(putModel1),
8      this.apiService.updateTask(putModel2)
9    ).pipe(
10      map(([first, second]) => {
11        // forkJoin returns an array of values, here we map those values to an object
12        console.log('results', first, second)
13        return { first, second };
14      })
15    );
16    // updateResults$.subscribe();
17    updateResults$.subscribe(
18      response => {
19        console.log(response);
20      },
21      err => {
22        this.recoverFromError(err);
23      });
24
25
26
27// Another Complex Example
28forkJoin(
29  this.http.get('some/api/welcomeMessage'),
30  language$,
31  dateRange$
32    .pipe(tap(([startDate, endDate]) => { 
33      this.startDate = startDate;
34      this.endDate = endDate;
35    })),
36  users$.pipe(tap(users => this.setUsers(users))),
37  this.http
38    .get('some/api/chart')
39    .pipe(tap(chart => this.chartData = chart))
40)
41.subscribe(([welcomeMsg, lang]) => {
42  this.setWelcomeMessage(welcomeMsg, lang);
43  // all data aquired, wire-up everything
44  this.launch();
45});

Created on 1/30/2019