Sub topic 11
Combining Streams with combineLatest, forkJoin, and withLatestFrom
Real screens rarely depend on a single stream. A product list might need both the server data and the current filter. A dashboard might need three HTTP responses before it can render. A save button might need the latest form value at the moment it is clicked. RxJS has a combination operator for each of these cases. They differ in when they emit and when they complete, and choosing the wrong one gives you bugs where nothing renders or data is stale.
This chapter assumes you know pipe, map, and catchError, how HttpClient returns observables that emit once and complete, and how the async pipe subscribes from a template.
The three behaviours at a glance
| Function | Emits when | First emission requires | Completes when | Typical Angular use |
|---|---|---|---|---|
| `combineLatest` | Any source emits | Every source has emitted at least once | All sources complete | Data plus filters, view models from several live streams |
| `forkJoin` | Once, at the end | Every source has completed | Right after its single emission | Parallel HTTP requests needed together |
| `withLatestFrom` | Only the primary source emits | Each secondary source has emitted at least once | The primary completes | Clicks or submits that read current state |
The key difference is which events trigger an emission. With combineLatest, every source can trigger one. forkJoin only reacts to completion. withLatestFrom has one source that triggers emissions, while the other sources only supply their latest values.
combineLatest: the latest value of everything
combineLatest takes an array (or an object) of observables. Once each source has emitted at least once, it emits an array holding the most recent value from each source. After that, every new value from any source produces a new array.
Run this in Node to see the timing:
import { combineLatest, interval, map, take } from 'rxjs';
const fast$ = interval(300).pipe(map(i => `fast${i}`), take(4));
const slow$ = interval(700).pipe(map(i => `slow${i}`), take(2));
combineLatest([fast$, slow$]).subscribe({
next: ([f, s]) => console.log(f, s),
complete: () => console.log('complete'),
});The output is:
fast1 slow0
fast2 slow0
fast3 slow0
fast3 slow1
completefast0 never appears. It arrived at 300 ms, before slow$ had emitted, and fast1 replaced it at 600 ms. combineLatest stores only the latest value from each source and does not queue earlier ones. It also keeps running after fast$ completes, because slow$ can still produce new combinations. It completes only when every source has completed.
A filtered list in Angular
The most common Angular pattern combines server data with user input:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { combineLatest, map, startWith } from 'rxjs';
interface Product {
id: number;
name: string;
category: string;
}
@Component({
selector: 'app-product-filter',
standalone: true,
imports: [ReactiveFormsModule, AsyncPipe],
template: `
<select [formControl]="category">
<option value="all">All</option>
<option value="books">Books</option>
<option value="games">Games</option>
</select>
@if (visible$ | async; as products) {
<ul>
@for (product of products; track product.id) {
<li>{{ product.name }}</li>
}
</ul>
}
`,
})
export class ProductFilterComponent {
private http = inject(HttpClient);
category = new FormControl('all', { nonNullable: true });
private products$ = this.http.get<Product[]>('/api/products');
private category$ = this.category.valueChanges.pipe(
startWith(this.category.value)
);
visible$ = combineLatest([this.products$, this.category$]).pipe(
map(([products, category]) =>
category === 'all'
? products
: products.filter(p => p.category === category)
)
);
}The HTTP observable emits once and completes. combineLatest keeps its last value and reuses it every time the category changes, so changing the filter does not send a new request.
The object form
Instead of an array, you can pass an object. The result then has named properties instead of tuple positions, which makes view models easier to read:
import { combineLatest, of } from 'rxjs';
combineLatest({ user: of('Ada'), theme: of('dark') }).subscribe(vm =>
console.log(vm.user, vm.theme)
);forkJoin accepts the same object form.
combineLatest gotchas
- Errors end everything. If any source errors, the combined stream errors and the other subscriptions are torn down. Put
catchErroron the individual source if you want the rest to keep working. - Glitches from shared ancestors. Suppose two sources are both derived from the same upstream observable. One upstream emission then produces two combined emissions, and the first of them pairs a new value with a stale one. If that intermediate state matters, compute both values from a single
mapinstead. - Empty input.
combineLatest([])completes immediately and never emits. This can happen when you build the array dynamically from a list that turns out to be empty. - Operator form.
source$.pipe(combineLatestWith(other$))does the same thing ascombineLatest([source$, other$])and reads better in the middle of a pipe.
forkJoin: wait for everything to finish
forkJoin subscribes to all sources in parallel. It waits until every source has completed, then emits one array or object containing each source's last value, and then completes. It works like Promise.all for observables, and it is the natural choice for a group of HTTP calls.
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { catchError, forkJoin, of } from 'rxjs';
interface Profile {
name: string;
}
interface Order {
id: number;
}
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [AsyncPipe],
template: `
@if (vm$ | async; as vm) {
<h2>Welcome, {{ vm.profile.name }}</h2>
<p>{{ vm.orders.length }} orders, {{ vm.notices.length }} notices</p>
} @else {
<p>Loading…</p>
}
`,
})
export class DashboardComponent {
private http = inject(HttpClient);
vm$ = forkJoin({
profile: this.http.get<Profile>('/api/me'),
orders: this.http
.get<Order[]>('/api/orders')
.pipe(catchError(() => of([] as Order[]))),
notices: this.http
.get<string[]>('/api/notices')
.pipe(catchError(() => of([] as string[]))),
});
}All three requests start at the same time, and the template renders once they have all finished. The profile request has no catchError on purpose: the page cannot work without it, so a profile failure should fail the whole result. The orders and notices requests fall back to empty lists, so a failure in either one does not block the dashboard.
forkJoin gotchas
- It never emits for streams that never complete.
forkJoinwithvalueChanges,interval, a router observable, or aBehaviorSubjectwill wait forever. Use it only with sources that complete, such asHttpClient,of,froman array, or anything followed bytake(1)orfirst(). - Only the last value counts. A source that emits three times and then completes contributes only its third value.
- A source that completes without emitting cancels the result. If any source completes without emitting (for example
EMPTY, or afilterthat removed everything),forkJoincompletes without emitting anything. AdddefaultIfEmpty(fallback)to sources where that can happen. - One unhandled error discards everything. The other results are lost even if those requests succeeded. Catch errors on each source when partial results are acceptable.
- Empty input.
forkJoin([])completes immediately without emitting. When you map an array of IDs to requests, handle the empty-array case separately.
withLatestFrom: one source drives, others supply values
withLatestFrom is a pipeable operator. Each time the primary source emits, it pairs that value with the latest values of the other sources. Emissions from the other sources only update the stored value and never trigger output on their own.
import { interval, take, withLatestFrom } from 'rxjs';
const clicks$ = interval(1000).pipe(take(3));
const latestValue$ = interval(450);
clicks$.pipe(withLatestFrom(latestValue$)).subscribe({
next: ([click, latest]) => console.log(`click ${click} saw ${latest}`),
complete: () => console.log('complete'),
});The output is:
click 0 saw 1
click 1 saw 3
click 2 saw 5
completelatestValue$ emits more often than clicks$, but only the click times produce output. When clicks$ completes, the result completes and withLatestFrom unsubscribes from latestValue$, even though latestValue$ itself never completes.
In Angular this fits actions that need the current state: a submit stream combined with the latest form value, or a "load more" trigger combined with the current filter. Compare it with combineLatest. If you combined a submit stream with the form value using combineLatest, every keystroke after the first submit would trigger a new save.
withLatestFrom gotchas
- Early primary values are dropped. If the primary emits before every secondary source has emitted, that emission is discarded without any error. A click that arrives before the HTTP data has loaded disappears. Give secondary sources an initial value with
startWith, or use a source that holds a current value. - It is not a request trigger.
withLatestFrom(this.http.get(...))subscribes to the request once, when the outer stream is subscribed. It does not send a new request per click. When each primary value should start a new request, useswitchMap,concatMap, orexhaustMapfrom the flattening chapter.
Choosing quickly
Ask two questions. First, do all the sources finish, and do you need only their final values? If yes, use forkJoin. If not, should a change in any source update the result? If yes, use combineLatest. If one stream represents events and the others represent state, use withLatestFrom.
Exercise
A component uses forkJoin([this.http.get('/api/items'), this.search.valueChanges]) and the template never renders. Why, and what should replace it?
Show answer
forkJoin emits only after every source completes, and valueChanges never completes. Use combineLatest([this.http.get('/api/items'), this.search.valueChanges.pipe(startWith(this.search.value))]). The startWith is needed because valueChanges does not emit the initial value, and combineLatest waits for every source to emit at least once.
Exercise
save$.pipe(withLatestFrom(this.settings$)) sends a save on each click. Users report that their first click right after the page loads does nothing. settings$ comes from an HTTP request. What is happening?
Show answer
The click arrived before settings$ had emitted. withLatestFrom drops primary emissions until every secondary source has a value. Fixes include disabling the button until the settings load, giving settings$ a default value with startWith, or, if every click should wait for the settings, using concatMap(() => this.settings$.pipe(take(1))) instead.
Exercise
You build forkJoin(ids.map(id => this.http.get(/api/items/${id}))). When ids is empty, the loading spinner never goes away. Explain and fix.
Show answer
forkJoin([]) completes immediately without emitting, so code that waits for a value never runs. Check for the empty case first, for example ids.length ? forkJoin(requests) : of([]), or add defaultIfEmpty([]) after the forkJoin.