Sub topic 11
Combining Streams with combineLatest, forkJoin, and withLatestFrom
This chapter assumes you already know pipe, map, the async pipe, takeUntilDestroyed, and how HttpClient returns observables. These three functions let you merge several streams into one, and each follows a different rule for when it emits.
How the three differ
| Function | Emits when | Completes when | Typical use |
|---|---|---|---|
| `forkJoin` | Every source has completed. It emits once, with each source's last value. | Right after that single emission | Parallel HTTP requests |
| `combineLatest` | Any source emits, as long as every source has emitted at least once | Every source has completed | View models built from several changing inputs |
| `withLatestFrom` | The main source emits. The other sources only supply their latest value. | The main source completes | A user action that needs the current state |
A dashboard using all three
The component below loads users and orders in parallel. It filters the users as the person types and logs an export whenever the button is clicked. The Subject named exportClicks turns clicks into a stream. Subjects get their own chapter later.
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, combineLatest, forkJoin, map, startWith, withLatestFrom } from 'rxjs';
interface User { id: number; name: string; }
interface Order { id: number; userId: number; total: number; }
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [AsyncPipe, ReactiveFormsModule],
template: `
<input [formControl]="filter" placeholder="Filter users" />
<button (click)="exportClicks.next()">Export</button>
@if (vm$ | async; as vm) {
<ul>
@for (user of vm.users; track user.id) {
<li>{{ user.name }}: {{ vm.orderCounts[user.id] ?? 0 }} orders</li>
}
</ul>
}
`,
})
export class DashboardComponent {
private http = inject(HttpClient);
filter = new FormControl('', { nonNullable: true });
exportClicks = new Subject<void>();
private term$ = this.filter.valueChanges.pipe(startWith(this.filter.value));
private data$ = forkJoin({
users: this.http.get<User[]>('/api/users'),
orders: this.http.get<Order[]>('/api/orders'),
});
vm$ = combineLatest([this.data$, this.term$]).pipe(
map(([{ users, orders }, term]) => {
const orderCounts: Record<number, number> = {};
for (const o of orders) {
orderCounts[o.userId] = (orderCounts[o.userId] ?? 0) + 1;
}
const needle = term.toLowerCase();
return {
users: users.filter(u => u.name.toLowerCase().includes(needle)),
orderCounts,
};
})
);
constructor() {
this.exportClicks
.pipe(withLatestFrom(this.term$), takeUntilDestroyed())
.subscribe(([, term]) => console.log(`Exporting users matching "${term}"`));
}
}The object form of forkJoin gives you named results, so you destructure { users, orders } and don't have to track array positions. HttpClient observables complete after one response, which is exactly what forkJoin needs.
Common errors
combineLatestnever emits. One source hasn't emitted yet. FormvalueChangesstays silent until the user types, so addstartWith(...)to give it a first value.forkJoinnever emits. A source never completes. Two examples areintervalandvalueChanges. UseforkJoinonly with sources that finish.forkJoinemits nothing at all. A source completed without emitting a value, for exampleEMPTY. In that caseforkJoincompletes empty.- One error kills the whole result. If any inner request fails, the combined stream errors. Put
catchErroron each request to keep partial results. withLatestFromdrops early clicks. Clicks are ignored until the secondary source has emitted once.
Exercise
A page needs the current user's profile and settings from two endpoints, and must re-render whenever a theme toggle observable emits. Which operators do you combine, and why?
Show answer
Use forkJoin for the two HTTP calls, because each completes after one response and you need both values. Then pass that result and the theme observable to combineLatest, so the view updates every time the theme changes. If the theme stream doesn't emit at first, give it startWith so combineLatest can produce its first value.
Exercise
Why would combineLatest([this.http.get('/a'), interval(1000)]) keep emitting, while forkJoin with the same sources never emits?
Show answer
combineLatest emits every time interval ticks, using the cached HTTP value. forkJoin waits for every source to complete, and interval never completes.