3. Combining Streams
merge, combineLatest, forkJoin, zip — coordinating multiple Observables
Real applications rarely have just one stream. A dashboard combines data from multiple API calls. A form's submit button should be disabled until all fields are valid and no save is in progress. A chat app merges messages from multiple channels into one feed. You need operators that coordinate multiple Observables.
RxJS provides several combination operators, each with different semantics. Choosing the wrong one is a common source of bugs, so this article explains exactly when each applies.
merge — Interleave Multiple Streams
merge subscribes to all input Observables simultaneously and forwards every emission from any of them into a single output stream. It's like merging highway on-ramps — all traffic flows into one lane.
import { merge, interval } from 'rxjs';
import { map, take } from 'rxjs/operators';
const fast$ = interval(500).pipe(map(() => 'FAST'), take(4));
const slow$ = interval(1000).pipe(map(() => 'SLOW'), take(3));
merge(fast$, slow$).subscribe(console.log);
// FAST (500ms)
// FAST (1000ms) — simultaneously:
// SLOW (1000ms)
// FAST (1500ms)
// FAST (2000ms)
// SLOW (2000ms)
// SLOW (3000ms)
The output completes only when all input Observables have completed.
Angular use case: combining event sources
@Component({
selector: 'app-notifications',
template: `<div *ngFor="let msg of messages">{{ msg }}</div>`
})
export class NotificationsComponent implements OnInit {
messages: string[] = [];
private destroy$ = new Subject<void>();
constructor(
private websocket: WebSocketService,
private push: PushNotificationService
) {}
ngOnInit() {
merge(
this.websocket.messages$,
this.push.notifications$.pipe(map(n => n.body))
).pipe(
takeUntil(this.destroy$)
).subscribe(msg => {
this.messages.unshift(msg);
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
Two independent streams — WebSocket messages and push notifications — merged into one feed.
combineLatest — React to Any Change
combineLatest waits until every input Observable has emitted at least once, then emits an array of the latest value from each. After that, it re-emits whenever any input changes.
import { combineLatest, of } from 'rxjs';
import { delay } from 'rxjs/operators';
const name$ = of('Alice').pipe(delay(100));
const age$ = of(30).pipe(delay(200));
const city$ = of('Berlin').pipe(delay(150));
combineLatest([name$, age$, city$]).subscribe(
([name, age, city]) => console.log(`${name}, ${age}, ${city}`)
);
// Alice, 30, Berlin (emitted at 200ms, when age$ — the last one — emits)
combineLatest timeline
a$: --1-----------3------|
b$: ------x---y----------|
out: ------[1,x]-[1,y]-[3,y]--|
Nothing emits until both a$ and b$ have produced a value.
After that, any change triggers a new combined emission.
Angular use case: reactive filtering
@Component({
selector: 'app-product-list',
template: `
<select [formControl]="category">
<option value="all">All</option>
<option value="electronics">Electronics</option>
<option value="books">Books</option>
</select>
<input [formControl]="search" placeholder="Search...">
<select [formControl]="sortBy">
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<div *ngFor="let product of filteredProducts$ | async">
{{ product.name }} - {{ product.price | currency }}
</div>
`
})
export class ProductListComponent implements OnInit {
category = new FormControl('all');
search = new FormControl('');
sortBy = new FormControl('name');
filteredProducts$: Observable<Product[]>;
constructor(private productService: ProductService) {}
ngOnInit() {
this.filteredProducts$ = combineLatest([
this.category.valueChanges.pipe(startWith('all')),
this.search.valueChanges.pipe(startWith(''), debounceTime(300)),
this.sortBy.valueChanges.pipe(startWith('name')),
this.productService.getProducts()
]).pipe(
map(([category, search, sortBy, products]) => {
let filtered = products;
if (category !== 'all') {
filtered = filtered.filter(p => p.category === category);
}
if (search) {
const term = search.toLowerCase();
filtered = filtered.filter(p =>
p.name.toLowerCase().includes(term)
);
}
return filtered.sort((a, b) =>
sortBy === 'price'
? a.price - b.price
: a.name.localeCompare(b.name)
);
})
);
}
}
Change the category, type a search term, or pick a sort order — combineLatest re-evaluates the filter with the latest values from all three controls plus the product data.
startWith is critical
combineLatest waits for all inputs to emit before producing output.
If any input hasn't emitted yet, nothing happens. That's why you'll almost always pair
form control streams with startWith — to provide an initial value immediately.
forkJoin — Wait for All to Complete
forkJoin waits for all input Observables to complete, then emits a single array containing the last value from each. Think of it as Promise.all for Observables.
import { forkJoin } from 'rxjs';
forkJoin([
this.http.get<User>('/api/user/1'),
this.http.get<Order[]>('/api/user/1/orders'),
this.http.get<Preferences>('/api/user/1/preferences')
]).subscribe(([user, orders, preferences]) => {
console.log('All loaded:', user.name, orders.length, preferences.theme);
});
All three HTTP requests fire in parallel. When the last one completes, you get all three results at once.
forkJoin and infinite streams
forkJoin requires every input to complete. If any input
Observable never completes (like a Subject or interval),
forkJoin will wait forever. Use it only with finite Observables.
Error handling with forkJoin
If any input Observable errors, forkJoin immediately errors and you lose all results — even from the requests that succeeded. Handle errors per-stream to prevent this:
forkJoin([
this.http.get<User>('/api/user/1').pipe(
catchError(() => of(null))
),
this.http.get<Order[]>('/api/user/1/orders').pipe(
catchError(() => of([]))
),
this.http.get<Preferences>('/api/user/1/preferences').pipe(
catchError(() => of(DEFAULT_PREFERENCES))
)
]).subscribe(([user, orders, preferences]) => {
// Each value is either real data or the fallback
if (user) {
this.user = user;
}
this.orders = orders;
this.preferences = preferences;
});
zip — Pair Values by Index
zip pairs up emissions by their position. The first emission from each input forms the first output, the second from each forms the second output, and so on. It waits until all inputs have emitted their Nth value before producing the Nth output.
import { zip, of, interval } from 'rxjs';
import { take, map } from 'rxjs/operators';
const letters$ = of('A', 'B', 'C');
const numbers$ = of(1, 2, 3);
const slow$ = interval(1000).pipe(take(3));
zip(letters$, numbers$, slow$).subscribe(
([letter, number, tick]) => console.log(letter, number, tick)
);
// A 1 0 (at 1s)
// B 2 1 (at 2s)
// C 3 2 (at 3s)
zip timeline
a$: --1-----2------3--|
b$: -----x-----y--------z--|
out: -----[1,x]--[2,y]---[3,z]--|
Each output waits for both inputs to have
produced their Nth value. No value is reused.
zip is less common than combineLatest but perfect when you're pairing streams that produce values at different rates and you want strict 1:1 correspondence.
Angular use case: pairing request and response timing
const requestTime$ = of(Date.now());
const response$ = this.http.get('/api/data');
zip(requestTime$, response$).pipe(
map(([start, data]) => ({
data,
latency: Date.now() - start
}))
).subscribe(({ data, latency }) => {
console.log(`Response received in ${latency}ms`);
this.data = data;
});
withLatestFrom — Main Stream + Snapshot
withLatestFrom is like combineLatest, but only one stream drives the output. The primary Observable controls when emissions happen; the other Observables just contribute their latest value at that moment.
import { fromEvent, interval } from 'rxjs';
import { withLatestFrom, map } from 'rxjs/operators';
const clicks$ = fromEvent(document, 'click');
const timer$ = interval(1000);
clicks$.pipe(
withLatestFrom(timer$),
map(([click, timerValue]) => `Clicked at timer: ${timerValue}`)
).subscribe(console.log);
// Only emits when the user clicks.
// The timer value is just a snapshot of whatever it was at click time.
The crucial difference from combineLatest: timer ticks alone don't produce output. Only clicks drive emissions.
Angular use case: save with current form state
this.saveButton.clicks$.pipe(
withLatestFrom(this.form.valueChanges),
switchMap(([_, formValue]) =>
this.http.post('/api/save', formValue)
)
).subscribe(() => console.log('saved'));
Clicks drive the save. The form value is just grabbed at the moment of the click.
Comparison Table
| Operator | Emits when | Requires completion? | Output per emission | Best for |
|---|---|---|---|---|
merge |
Any input emits | No | Single value from whichever emitted | Interleaving independent streams |
combineLatest |
Any input emits (after all have emitted once) | No | Array of latest from each | Reactive recalculation from multiple inputs |
forkJoin |
All inputs complete | Yes | Single array of final values | Parallel HTTP requests (Promise.all) |
zip |
All inputs have an Nth value | No | Array of Nth values paired | Strict positional pairing |
withLatestFrom |
Primary input emits | No | Array: primary value + snapshots | Event-driven with context |
Try It Yourself — Stream Combiner
Two source streams (A and B) emit values at different times. Pick a combining operator and watch how it produces output. Dashed lines connect source marbles to the output marbles they contributed to — this is where the differences really show.
A emits A1 at 0.5s, A2 at 1.5s, A3 at 3s (completes at 3.5s). B emits B1 at 1s, B2 at 2s (completes at 2.5s).
Event log
Nested Combinations
These operators compose. Here's a dashboard that loads initial data, then reacts to filter changes:
@Component({
selector: 'app-dashboard',
template: `
<app-filters (changed)="onFilterChange($event)"></app-filters>
<app-chart [data]="chartData$ | async"></app-chart>
<app-table [rows]="tableData$ | async"></app-table>
`
})
export class DashboardComponent implements OnInit {
private filters$ = new BehaviorSubject<Filters>(DEFAULT_FILTERS);
chartData$: Observable<ChartData>;
tableData$: Observable<TableRow[]>;
ngOnInit() {
// Load reference data once
const refData$ = forkJoin([
this.http.get<Category[]>('/api/categories'),
this.http.get<Region[]>('/api/regions')
]).pipe(shareReplay(1));
// Combine filters with reference data, then fetch filtered results
const combined$ = combineLatest([
this.filters$.pipe(debounceTime(200)),
refData$
]).pipe(
switchMap(([filters, [categories, regions]]) =>
forkJoin([
this.http.get<ChartData>('/api/chart', { params: filters }),
this.http.get<TableRow[]>('/api/table', { params: filters })
])
),
shareReplay(1)
);
this.chartData$ = combined$.pipe(map(([chart, _]) => chart));
this.tableData$ = combined$.pipe(map(([_, table]) => table));
}
onFilterChange(filters: Filters) {
this.filters$.next(filters);
}
}
forkJoin loads reference data once. combineLatest reacts when filters change. switchMap cancels stale requests. shareReplay prevents duplicate subscriptions. Each operator does one thing, and together they handle a complex data-flow.
What's Next
You can now create, transform, and combine streams. The next article covers Angular services — how to encapsulate reactive logic in injectable services and connect them to components.