Subscribing to Multiple Observables in Angular Components
Angular applications heavily rely on RxJS Observables. While building large front end apps with these technologies we quickly will need to learn how to manage subscribing to multiple Observables in our components. In this post we are going to cover five different ways to subscribe to multiple Observables and the pros and cons of each.
In our component, we will have three Observables. Each Observable has slightly different behavior. The first
Observable emits a single value immediately. The second
Observable emits a single value after a couple of seconds. The third
Observable emits multiple values one value every second. Below are some functions that return the Observables that we will use in our components.
import { Observable, of, interval } from 'rxjs';
import { delay } from 'rxjs/operators';
export function getSingleValueObservable() {
return of('single value');
}
export function getDelayedValueObservable() {
return of('delayed value').pipe(delay(2000));
}
export function getMultiValueObservable() {
return new Observable<number>(observer => {
let count = 0;
const interval = setInterval(() => {
observer.next(count++);
console.log('interval fired');
}, 1000);
return () => {
clearInterval(interval);
};
});
}
Manual Subscriptions
Let's take a look at our component TypeScript to see our multiple Observables used with our first technique of subscribing directly to our component.
import { Component } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
import {
getSingleValueObservable,
getDelayedValueObservable,
getMultiValueObservable
} from './../util';
@Component({
selector: 'app-manual-subscriptions',
template: `
<p>{{first}}</p>
<p>{{second}}</p>
<p>{{third}}</p>
`
})
export class ManualSubscriptionsComponent {
first: string;
second: string;
third: number;
thirdSubscription: Subscription;
ngOnInit() {
getSingleValueObservable()
.subscribe(value => this.first = value);
getDelayedValueObservable()
.subscribe(value => this.second = value);
this.thirdSubscription = getMultiValueObservable()
.subscribe(value => this.third = value);
}
// Multi value observables must manually
// unsubscribe to prevent memory leaks.
ngOnDestroy() {
this.thirdSubscription.unsubscribe();
}
}
In this component we simply call .subscribe()
to get the events from our Observables. When first working with Angular and RxJS subscribing directly to the Observable is where most users start.
The pros to this are it's simple and works well for single values. The cons to
this are if our Observable has multiple values we must manually unsubscribe with ngOnDestroy
life cycle hook. If we don't unsubscribe from an Observable when the component is destroyed, we will leave memory leaks. If you remove the .unsubscribe()
in the working demo, you will see this behavior when the *ngIf removes the component
. In our later examples, we will see how Angular can help us manage our Rx subscriptions.
Async Pipe
In this next example, we will see how Angular has a built-in template syntax that cleans up our prior component quite a bit. With Angular, we can use the async pipe feature. The Async pipe will allow us to let angular know what properties on our component are Observables so it can automatically subscribe and unsubscribe to our component for us. Let's take a look at the component.
import { Component } from '@angular/core';
import {
getSingleValueObservable,
getDelayedValueObservable,
getMultiValueObservable
} from './../util';
@Component({
selector: 'app-async-pipe',
templateUrl: './async-pipe.component.html'
})
export class AsyncPipeComponent {
show = false;
first$ = getSingleValueObservable();
second$ = getDelayedValueObservable();
third$ = getMultiValueObservable();
}
As you can see our component, we directly assign the result of our function to the properties of our component. Our Observables are using the convention to end with a $
to help distinguish what is an Observable vs. a primitive for learning purposes.
<h2>Async Pipe</h2>
<button (click)="show = !show">Toggle</button>
<ng-container *ngIf="show">
<p>{{first$ | async}}</p>
<p>{{second$ | async}}</p>
<p>multi values {{third$ | async}}</p>
</ng-container>
As we can see in our template, the async
pipe automatically subscribes and handles our Observables. The pros to this are we can let Angular do the heavy lifting to our Observables. The cons are that this syntax become a bit more complicated when we have multiple subscriptions. In a later step, we will see how we can improve on this.
ForkJoin and *ngIf
Sometimes we need to subscribe to multiple Observables at once. A typical scenario is when using multiple HTTP requests. In this example, we will use the RxJS operator ForkJoin.
import { Component, OnInit } from '@angular/core';
import { forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';
import {
getSingleValueObservable,
getDelayedValueObservable,
getMultiValueObservable
} from './../util';
@Component({
selector: 'app-fork-join-operator',
templateUrl: './fork-join-operator.component.html'
})
export class ForkJoinOperatorComponent {
show = false;
values$ = forkJoin(
getSingleValueObservable(),
getDelayedValueObservable()
// getMultiValueObservable(), forkJoin on works for observables that complete
).pipe(
map(([first, second]) => {
// forkJoin returns an array of values, here we map those values to an object
return { first, second };
})
);
}
In our component, we use forkJoin
to combine the Observables into a single value Observable. The forkJoin
operator will subscribe to each Observable passed into it. Once it receives a value from all the Observables, it will emit a new value with the combined values of each Observable. ForkJoin works well for single value Observables like Angular HttpClient. ForkJoin can be comparable to Promise.All()
.
<h2>forkJoin Operator</h2>
<button (click)="show = !show">Toggle</button>
<ng-container *ngIf="show">
<ng-container *ngIf="values$ | async; let values;">
<p>{{values.first}}</p>
<p>{{values.second}}</p>
<p>{{values.third}}</p>
</ng-container>
</ng-container>
In our template, we are going to leverage a few Angular template features to handle our Observables. First, our ng-container
allows us to use Angular directives like *ngIf
without generating HTML like excessive div
elements. Next, we use a *ngIf
feature that allows us to subscribe with the async pipe and then assign the value from the Observable into a temporary template variable that we can reuse in our template, so we don't have to repeat the async
pipe syntax multiple times.
If you take note with the ForkJoin, we don't get any values rendered until all Observables pass back a value. In our working demo, we don't see any values until the delayed Observable emits its value. This technique allows us to clean up our template by subscribing once letting Angular handle our subscription while referencing our Observable multiple times. The issue we see here is that forkJoin
limits us to single value Observables only. The next example we will see how to handle multi-value Observables.
Combine Latest and *ngIf
This example will use an operator called combineLatest
this is similar to forkJoin
but allows Observables with multiple values. Let's take a look at the component TypeScript.
import { Component, OnInit } from '@angular/core';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import {
getSingleValueObservable,
getDelayedValueObservable,
getMultiValueObservable
} from './../util';
@Component({
selector: 'app-combine-latest-operator',
templateUrl: './combine-latest-operator.component.html'
})
export class CombineLatestOperatorComponent {
show = false;
values$ = combineLatest(
getSingleValueObservable(),
getDelayedValueObservable(),
getMultiValueObservable()
).pipe(
map(([first, second, third]) => {
// combineLatest returns an array of values, here we map those values to an object
return { first, second, third };
})
);
}
As we can see combineLatest
is very similar to forkJoin
. Combine Latest will emit the single combined value as soon as at least every Observable emits a single value and will continue emitting multiple values with the latest of each.
<h2>combineLatest Operator</h2>
<button (click)="show = !show">Toggle</button>
<ng-container *ngIf="show">
<ng-container *ngIf="values$ | async; let values;">
<p>{{values.first}}</p>
<p>{{values.second}}</p>
<p>{{values.third}}</p>
</ng-container>
</ng-container>
In the template, we use the same technique with *ngIf
and the async pipe. Next, let's look at a use case of where we want to subscribe to multiple different Observables without the use of forkJoin
or combineLatest
.
Subscribing with Async Pipe Objects
In this example, we will use the Async pipe but show how we can subscribe to multiple Observables in the template instead of the component TypeScript.
import { Component } from '@angular/core';
import {
getSingleValueObservable,
getDelayedValueObservable,
getMultiValueObservable
} from './../util';
@Component({
selector: 'app-async-pipe-object',
templateUrl: './async-pipe-object.component.html'
})
export class AsyncPipeObjectComponent {
show = false;
first$ = getSingleValueObservable();
second$ = getDelayedValueObservable();
third$ = getMultiValueObservable();
}
Our component TypeScript is similar to our earlier examples. The template is where things get interesting.
<h2>Async Pipe Object</h2>
<button (click)="show = !show">Toggle</button>
<ng-container *ngIf="show">
<ng-container
*ngIf="{ first: first$ | async, second: second$ | async, third: third$ | async } as values;"
>
<p>{{values.first}}</p>
<p>{{values.second}}</p>
<p>multi values {{values.third}}</p>
</ng-container>
</ng-container>
Using *ngIf
and the async pipe we can unwrap each Observable into a single value object that contains the unwrapped value of each Observable. This use of *ngIf
is not a well-known ability of the Angular template syntax but allows an easy way to subscribe to multiple Observables in our template as well as reference to it numerous times.
As we can see, there are many ways to subscribe to Observables in Angular each with pros and cons. Take a look at the working demos below!