RxJS 08 ๐ฃ Combining & Joining Streams โ Orchestrating concurrent streams with combineLatest, forkJoin, merge, concat, and withLatestFrom
A combining operator takes several independent streams and produces one. That sentence describes five different operators, and the only way to tell them apart is to ask two questions about each: when does the combined stream emit, and in what order do the values arrive. merge emits whenever any source emits, in arrival order. concat emits whenever the current source emits, in declaration order, and never overlaps. combineLatest emits whenever any source emits, carrying the latest value of every source. forkJoin emits exactly once, after every source completes. withLatestFrom emits only when one designated source emits, carrying the latest value of the others.
The confusion is that on a slow test all five look the same โ an array shows up at the end. The differences only surface when the sources are live: a chatty mousemove next to a rarely-changing form field, an HTTP call that never completes, a stream that fires before its partner has produced anything. Those are the conditions in production, and they turn the wrong choice into a busy render loop, a request that never fires, or a screen that stays empty with no error in the console.
This chapter covers the five operators named in the title plus their near neighbours zip and race, the pipeable *With variants, and startWith, which is the usual companion to any of them. It starts with why combination is its own problem separate from flattening, then walks through each operator’s emission rule, then assembles a session where all five run against real DOM and HTTP sources.
Key point: a combining operator is defined by its emission trigger and its completion rule, not by what it does with the values. merge and combineLatest and withLatestFrom all re-emit on a source change; forkJoin and concat do not. merge and combineLatest need every source alive; forkJoin needs every source to die. Getting the trigger right is the whole job.
Why combining operators exist
The multi-source-UI problem. A single screen is rarely driven by one stream. A filter panel has a search field, a category select, and a sort order. A toolbar has a selection stream and a click stream. A dashboard has four endpoints that must load together. Emitting state from each stream into a shared variable and re-rendering on every change is possible, and it is what most imperative code does, and it produces a render that fires three times for one user action. A combining operator gives the panel one stream instead of three.
The stale-state problem. The classic bug is a handler that reads a variable captured at subscription time. The user opens the panel when the category is “all”, changes it to “books”, then clicks search โ and the handler still uses “all” because that is what the closure saw. withLatestFrom(category$) and combineLatest([term$, category$]) exist precisely so the current value is read at the moment of the event, not at the moment of subscription.
The parallel-loading problem. Sequential HTTP calls are a latency bug. Requesting the user, then the settings, then the notifications, then the feature flags is four round trips stacked end to end. forkJoin issues all four at once and joins them on completion, which is the RxJS spelling of Promise.all. The operator exists because the imperative equivalent โ manual counters, Promise.all, or four nested callbacks โ is exactly what a reactive UI should not contain.
The ordering problem. Some streams must be consumed strictly in order. A boot sequence that loads configuration before opening a socket before starting a poller cannot tolerate the socket opening early. concat encodes that dependency in the stream rather than in a chain of callbacks, and the resulting code reads top to bottom in the order it executes.
The completion problem. forkJoin hangs forever if any input never completes. combineLatest produces nothing if any input never emits. concat never reaches its second source if the first never completes. These are not edge cases; fromEvent never completes and interval never completes, so a naive forkJoin(fromEvent(...), http.get(...)) is dead code that looks correct. Knowing each operator’s completion requirement is half of knowing the operator.
The chatty-stream problem. combineLatest([formValue$, mouseMove$]) fires on every mouse move, forty to a thousand times per second, and each emission runs the downstream operator. withLatestFrom exists to make one side a trigger and the other a state source, so the chatty side is read rather than listened to. This is the single most common performance bug in the family, and it is invisible in tests that never move the mouse.
a. merge โ interleaving by arrival
merge(...sources) subscribes to every source immediately and forwards each value the instant it is produced. There is no ordering, no buffering, and no coordination. The output order is the arrival order, which for genuinely concurrent sources is not deterministic. merge completes only when all sources complete, and it errors the instant any source errors, unsubscribing the rest.
import { merge, fromEvent, map } from 'rxjs';
const keydown$ = fromEvent<KeyboardEvent>(document, 'keydown');
const click$ = fromEvent<MouseEvent>(document, 'click');
const scroll$ = fromEvent(window, 'scroll', { passive: true });
// All three are subscribed at once; whichever fires first wins
merge(keydown$, click$, scroll$)
.subscribe(() => {
// Any of the three user actions resets the idle timer
resetIdleTimer();
});
The values are whatever the sources produce, so when the types differ the union narrows to a common shape. A cleaner pattern is to map each source into a discriminated union before merging, so the subscriber can switch on type with full type safety.
import { merge } from 'rxjs';
import { map } from 'rxjs/operators';
// Each source gets a literal `type` tag before it is merged
const activity$ = merge(
keydown$.pipe(map(() => ({ type: 'key' as const }))),
click$.pipe(map(() => ({ type: 'click' as const }))),
scroll$.pipe(map(() => ({ type: 'scroll' as const })))
);
activity$.subscribe((event) => {
// `event.type` is 'key' | 'click' | 'scroll'
telemetry.track(event.type);
});
merge has no concurrency control. When the sources are observables-of-observables, the flattening form mergeAll(n) caps how many are subscribed at once, and mergeAll(1) is exactly concatAll(). For the array-of-sources case, mergeMap(fn, n) over from(array) is the capped equivalent.
import { from, mergeMap } from 'rxjs';
// Capped fan-out: merge does not have this knob, mergeMap does
from(urls)
.pipe(mergeMap((url) => fetchJson(url), 3))
.subscribe((json) => results.push(json));
The pipeable variant is mergeWith, which merges the receiver with the arguments and reads better in a long pipe.
import { fromEvent } from 'rxjs';
import { mergeWith, debounceTime } from 'rxjs/operators';
fromEvent(document, 'keydown')
.pipe(
// Same behaviour as merge, written as a pipe step
mergeWith(fromEvent(document, 'click')),
debounceTime(500)
)
.subscribe(() => idle());
b. concat โ serialising by subscription
concat(...sources) subscribes to the first source and waits for it to complete before subscribing to the second. There is no interleaving, no parallelism, and no overlap: at any moment exactly one source is active. The output is therefore in declaration order, and the total duration is the sum of every source’s duration.
import { concat, of, timer } from 'rxjs';
import { map } from 'rxjs/operators';
// The three steps run strictly one after another
concat(
of('boot').pipe(map((s) => step(s, 300))),
of('config').pipe(map((s) => step(s, 200))),
of('socket').pipe(map((s) => step(s, 500)))
).subscribe({
next: (name) => console.log('finished', name),
complete: () => console.log('app ready')
});
The failure mode is the most important thing to know about concat: if the first source never completes, the second source is never subscribed and is never even executed. This is not an error and produces no warning. It is the reason concat(interval(1000), doSomething()) does nothing.
import { concat, interval, of } from 'rxjs';
import { take } from 'rxjs/operators';
// DANGER: interval never completes, so 'never runs' is never printed
concat(interval(1000), of('never runs')).subscribe(console.log);
// SAFE: take(n) makes the first source finite
concat(interval(1000).pipe(take(3)), of('runs after 3s'))
.subscribe((v) => console.log(v));
The pipeable form is concatWith. It is the natural way to append a completion action โ a request to flush the queue, a telemetry call, a redirect โ to a stream that you know is finite.
import { from } from 'rxjs';
import { concatWith, map } from 'rxjs/operators';
from([1, 2, 3])
.pipe(
map((n) => n * 10),
// Runs after the source completes, never before
concatWith(from(['a', 'b']))
)
.subscribe((v) => console.log(v)); // 10, 20, 30, 'a', 'b'
concat is also the right tool for a queue of dependent operations that arrive over time. When the sources are produced dynamically, concatMap is the operator โ it is concat applied per outer value, one at a time.
c. combineLatest โ latest from each, on any change
combineLatest(sources) subscribes to all sources, waits until every source has emitted at least once, and after that emits an array of the latest values from each on every emission from any source. It completes only when every source completes, and errors as soon as any source errors.
import { combineLatest } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
const term$ = fromEvent(searchEl, 'input').pipe(
map(() => searchEl.value.trim()),
startWith('') // seed so the combine can fire early
);
const sort$ = sortSelect$.pipe(startWith('relevance'));
const filter$ = category$.pipe(startWith('all'));
combineLatest([term$, sort$, filter$])
.pipe(
// The array order matches the source order
map(([term, sort, filter]) => ({ term, sort, filter }))
)
.subscribe((criteria) => {
// Fires on any of the three changing, with the other two current
renderCriteria(criteria);
});
Every emission is a full snapshot. There is no partial-update mode: when a keystroke arrives, combineLatest re-reads sort$‘s last value and filter$‘s last value and emits all three together. That is what makes it correct for form state and wrong for anything chatty โ a keystroke also means a full downstream pass.
The startWith calls above are not decorative. Without them, nothing emits until the user has typed and changed the sort and changed the filter, because combineLatest needs one value from each source before it can produce its first array. Seeding with a default is the standard fix and belongs in every combineLatest over form inputs.
The chatty-stream failure is worth showing explicitly.
import { combineLatest } from 'rxjs';
// BAD: every mousemove creates a fresh [value, x, y] tuple
combineLatest([formValue$, fromEvent(document, 'mousemove')])
.subscribe(([value, event]) => {
// runs hundreds of times per second while the pointer moves
persist(value, event.clientX, event.clientY);
});
The fix is withLatestFrom, covered later, or a debounceTime on the combined output. combineLatest is a sum of noise; withLatestFrom is a trigger.
The pipeable variant combineLatestWith attaches one or more sources to an existing stream, which keeps the primary source at the head of the pipe. Note that in RxJS 7 the result-selector argument was removed from combineLatest; use map on the emitted array instead.
d. forkJoin โ final value of each, on completion of all
forkJoin(sources) subscribes to all sources at once and waits for all of them to complete. When the last one completes, it emits a single array (or object) containing the final value of each source, then completes immediately. It emits exactly once, ever.
import { forkJoin } from 'rxjs';
forkJoin({
user: http.get<User>('/api/user'),
settings: http.get<Settings>('/api/settings'),
flags: http.get<string[]>('/api/flags'),
permissions: http.get<Permission[]>('/api/permissions')
})
.subscribe(({ user, settings, flags, permissions }) => {
// All four requests ran in parallel; this fires once when the
// slowest one completes, with all four results available
renderDashboard(user, settings, flags, permissions);
});
The object form is the readable one: the keys come out as named properties instead of positional array entries, so the callback signature survives a reorder. Angular’s HttpClient calls complete after emitting, which is what makes them legal operands.
The operand rule is the whole contract: a source that never completes blocks the emission forever.
import { forkJoin, fromEvent } from 'rxjs';
// BUG: fromEvent never completes, so this subscriber never runs
forkJoin([
http.get('/api/config'),
fromEvent(document, 'click') // never completes
]).subscribe(console.log); // never called
Two behaviours follow from “emits once, on completion”. A source that completes without emitting anything means the join has no value for that slot, and the result completes without emitting โ which looks identical to the bug above and is just as hard to spot. And because forkJoin fires only once, it is not suitable for anything that must react to updates; that is combineLatest‘s job.
The most important non-obvious case is a partially failing join. When one operand errors, forkJoin errors and discards the rest, which is a real problem for a dashboard where three of four panels could render. The fix is per-operand catchError returning a fallback.
forkJoin({
user: http.get<User>('/api/user'),
// A failing settings call falls back to a default instead of
// tearing down the whole dashboard
settings: http.get<Settings>('/api/settings').pipe(
catchError(() => of(defaultSettings))
)
}).subscribe(({ user, settings }) => render(user, settings));
e. withLatestFrom โ sample a stream on a trigger
withLatestFrom(...others) is the operator for “when the trigger fires, tell me what the others currently are”. The receiver is the trigger; the arguments are sampled. Only the trigger’s emissions produce output, and only the trigger’s completion completes the result. The sampled streams are subscribed but their emissions are read, never forwarded.
import { fromEvent } from 'rxjs';
import { withLatestFrom, map } from 'rxjs/operators';
const save$ = fromEvent(saveBtn, 'click');
const user$ = session.pipe(map((s) => s.user));
const doc$ = editor$.pipe(map((d) => d.serialize()));
save$
.pipe(
// The click is the trigger; the user and doc are sampled at that
// exact moment, not captured when this pipeline was created
withLatestFrom(user$, doc$),
map(([_click, user, doc]) => ({ owner: user.id, body: doc }))
)
.subscribe((payload) => http.post('/api/save', payload));
The sample is taken at trigger time. That is the entire reason the operator exists: a handler that closes over user reads the value from subscription time, and a handler that calls getUser() reads it imperatively. withLatestFrom reads the stream’s current value at the instant of the event, which is what a reactive UI actually needs.
The critical caveat is that if a sampled stream has never emitted, the trigger is swallowed. The emission is dropped, not buffered and not queued, and no error is raised.
import { of } from 'rxjs';
import { withLatestFrom, startWith } from 'rxjs/operators';
const settings$ = http.get<Settings>('/api/settings'); // slow
// BUG: clicks before the settings response lands are silently lost
click$.pipe(
withLatestFrom(settings$)
).subscribe(([_c, s]) => apply(s));
// FIX: seed the sampled stream so a trigger always has something to read
click$.pipe(
withLatestFrom(settings$.pipe(startWith(defaultSettings)))
).subscribe(([_c, s]) => apply(s));
withLatestFrom does not complete when a sampled stream completes โ a completed sample simply stops updating, and the trigger keeps driving. It does complete when the trigger completes. This asymmetry is why withLatestFrom is safe with a long-lived trigger and a finite sample, while the reverse would end the stream early.
Two or more sampled streams are passed as additional arguments. In RxJS 7 the result-selector argument was removed, so the emitted tuple is an array of [triggerValue, ...sampledValues] and a map reshapes it.
f. zip, race, and the pipeable variants
zip(...sources) pairs by index. It waits until every source has produced its n-th value and then emits the tuple of n-th values. When one source runs out and no further tuples can be formed, the result completes. It is the operator for correlation, not for timing.
import { zip, from } from 'rxjs';
const ids$ = from([101, 102, 103]);
const bodies$ = from([`{'a':1}`, `{'b':2}`, `{'c':3}`]);
// Pairs the nth id with the nth body; total emissions = min(lengths)
zip(ids$, bodies$).subscribe(([id, body]) => {
console.log(id, '->', body); // 101 -> {...}, 102 -> {...}, ...
});
race(...sources) subscribes to all of them and then mirrors whichever emits or notifies first, unsubscribing the rest. It is the operator for a failover or a timeout race.
import { race, timer, throwError } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
// Whichever answers first wins; the loser is unsubscribed
race(
http.get('/api/primary'),
http.get('/api/mirror')
).subscribe((data) => render(data));
// A timeout is the same idea with a throwing branch
race(http.get('/api/slow'), timer(3000).pipe(
mergeMap(() => throwError(() => new Error('timeout')))
)).subscribe(...);
Every operator in this chapter has a pipeable twin, and the pipeable form is the one to use inside a longer pipe because it keeps the primary source where the reader expects it. mergeWith, concatWith, combineLatestWith, zipWith, raceWith all take the same arguments as their static counterparts and attach to the receiver. withLatestFrom has no static form โ it is already an operator that knows which side is the trigger. forkJoin has no pipeable form, because its whole purpose is to wait for completion and there is no receiver left afterwards.
startWith(...values) deserves its own mention because it is the operator attached to almost every combination. It prepends synchronous values to a stream, which means it runs before the source is even subscribed. Its two uses are the one already shown โ seeding a combineLatest operand so the combine can fire โ and giving a subject an initial state so late subscribers see something. It is not concat: concat(first$, source$) waits for first$ to complete before subscribing to source$, while source$.pipe(startWith(v)) emits v first and then behaves exactly like source$.
Complete Example Session
// ============================================
// PART 1: IMPORTS AND SHARED SOURCES
// ============================================
import { merge, concat, combineLatest, forkJoin, zip, race, of } from 'rxjs';
import {
map, startWith, take, withLatestFrom, catchError,
mergeWith, concatWith, mergeMap, debounceTime, distinctUntilChanged
} from 'rxjs/operators';
const searchEl = document.querySelector<HTMLInputElement>('#search')!;
const saveBtn = document.querySelector<HTMLButtonElement>('#save')!;
const sortSelect = document.querySelector<HTMLSelectElement>('#sort')!;
const keydown$ = fromEvent<KeyboardEvent>(document, 'keydown');
const click$ = fromEvent<MouseEvent>(document, 'click');
const scroll$ = fromEvent(window, 'scroll', { passive: true });
// ============================================
// PART 2: merge - MANY SOURCES, ONE IDLE TIMER
// ============================================
merge(
keydown$.pipe(map(() => ({ type: 'key' as const }))),
click$.pipe(map(() => ({ type: 'click' as const }))),
scroll$.pipe(map(() => ({ type: 'scroll' as const })))
).subscribe((event) => {
// Any activity from any source keeps the session alive
resetIdleTimer();
telemetry.track(event.type);
});
// ============================================
// PART 3: concat - THE BOOT SEQUENCE
// ============================================
concat(
http.get<Config>('/api/config'), // 1. must finish first
http.post('/api/session', token), // 2. needs the config
of('ready') // 3. runs only after both
).pipe(
// take(1) style guard is not needed: HttpClient completes
concatWith(of('boot-complete'))
).subscribe({
next: (step) => setBootStep(String(step)),
complete: () => hideSplash()
});
// ============================================
// PART 4: combineLatest - THE FILTER PANEL
// ============================================
const term$ = fromEvent(searchEl, 'input').pipe(
map(() => searchEl.value.trim()),
startWith('')
);
const sort$ = fromEvent(sortSelect, 'change').pipe(
map(() => sortSelect.value),
startWith('relevance')
);
combineLatest([term$, sort$])
.pipe(
map(([term, sort]) => ({ term, sort })),
debounceTime(200), // collapse the burst from typing
distinctUntilChanged((a, b) =>
a.term === b.term && a.sort === b.sort)
)
.subscribe((criteria) => runSearch(criteria));
// ============================================
// PART 5: forkJoin - THE DASHBOARD LOAD
// ============================================
forkJoin({
user: http.get<User>('/api/user'),
settings: http.get<Settings>('/api/settings').pipe(
catchError(() => of(defaultSettings)) // one failure does not
), // kill the dashboard
flags: http.get<string[]>('/api/flags')
}).subscribe(({ user, settings, flags }) => {
// Fired once, when the slowest of the three completed
renderDashboard(user, settings, flags);
});
// ============================================
// PART 6: withLatestFrom - THE TOOLBAR ACTION
// ============================================
const selection$ = store.select<Row[]>('selection');
fromEvent(saveBtn, 'click').pipe(
// The click is the trigger; the selection is read at that moment
withLatestFrom(selection$),
map(([_click, rows]) => rows.map((r) => r.id))
).subscribe((ids) => http.post('/api/batch-save', { ids }));
// ============================================
// PART 7: zip - REQUEST/RESPONSE PAIRING
// ============================================
zip(
from([1, 2, 3]), // nth request
from(['a', 'b', 'c']) // nth response
).subscribe(([req, res]) => matchLog(req, res));
// ============================================
// PART 8: race - FIRST MIRROR TO ANSWER
// ============================================
race(
http.get('/api/primary'),
http.get('/api/mirror')
).subscribe({
next: (data) => render(data),
error: () => renderFallback()
});
// ============================================
// PART 9: THE CHATTY-STREAM FIX
// ============================================
// BAD: combineLatest over a mousemove fires on every pixel
combineLatest([term$, fromEvent(document, 'mousemove')])
.subscribe(([term, event]) => track(term, event.clientX));
// GOOD: the form is the trigger; the pointer is only sampled
term$.pipe(
withLatestFrom(fromEvent(document, 'mousemove')),
map(([term, event]) => ({ term, x: event.clientX }))
).subscribe((sample) => track(sample.term, sample.x));
// ============================================
// PART 10: THE ASSEMBLED PIPELINE
// ============================================
const activity$ = merge(keydown$, click$, scroll$).pipe(
map(() => Date.now())
);
const criteria$ = combineLatest([term$, sort$]).pipe(
map(([term, sort]) => ({ term, sort }))
);
const results$ = criteria$.pipe(
mergeMap((c) => http.get<Result[]>(`/api/search?q=${c.term}&s=${c.sort}`))
);
const boot$ = concat(
http.get<Config>('/api/config'),
of('ready')
);
boot$.subscribe(() => {
// Only after boot do the long-lived streams subscribe
activity$.subscribe(resetIdleTimer);
results$.subscribe(renderResults);
});
The ten parts built an idle timer from three merged event families, a sequential boot with concat, a filter panel with combineLatest plus a debounce guard, a parallel dashboard with forkJoin and per-key error fallbacks, a toolbar action that samples the live selection with withLatestFrom, an index pairing with zip, a failover with race, the chatty-stream fix side by side, and an assembled pipeline that gates the long-lived subscriptions behind the boot sequence.
Quick Reference
The Five Operators
| Operator | Emits when | Emits how many | Order |
|---|---|---|---|
merge | any source emits | unbounded | arrival |
concat | the current source emits | unbounded | declaration |
combineLatest | any source emits, once all have | unbounded | any, tuple |
forkJoin | all sources complete | exactly one | tuple |
withLatestFrom | the trigger emits | one per trigger | tuple |
Preconditions and Completion
| Operator | Needs every source to emit first | Needs every source to complete | Completes when |
|---|---|---|---|
merge | no | no | all complete |
concat | no | yes, per source | last source completes |
combineLatest | yes | no | all complete |
forkJoin | no (but needs a value) | yes | last completes, then emits |
withLatestFrom | yes, for samples | no | the trigger completes |
Static and Pipeable Forms
| Static | Pipeable | Notes |
|---|---|---|
merge(a, b) | a.pipe(mergeWith(b)) | pipeable keeps the receiver |
concat(a, b) | a.pipe(concatWith(b)) | a must complete |
combineLatest([a, b]) | a.pipe(combineLatestWith(b)) | map replaces the result selector |
zip(a, b) | a.pipe(zipWith(b)) | pairs by index |
race(a, b) | a.pipe(raceWith(b)) | first to notify wins |
| โ | a.pipe(withLatestFrom(b)) | trigger plus samples |
forkJoin({...}) | โ | no pipeable form |
Seeding and Guarding
| Situation | Fix |
|---|---|
combineLatest never fires | startWith(default) on each operand |
withLatestFrom drops triggers | startWith(default) on the sample |
forkJoin never fires | remove non-completing sources |
| Chatty combined stream | debounceTime or withLatestFrom |
One failing forkJoin operand | catchError inside that operand |
| Duplicate emitted arrays | distinctUntilChanged with a comparator |
Best Practices
โ Do This:
// Seed every combineLatest operand so the first emission can happen
combineLatest([term$.pipe(startWith('')), sort$.pipe(startWith('a'))]); // โ
// Tag each merged source so the subscriber can discriminate
merge(a$.pipe(map(() => ({t: 'a' as const}))), b$.pipe(map(...))); // โ
// Sample live state at trigger time instead of closing over it
click$.pipe(withLatestFrom(selection$), map(([, s]) => s)); // โ
// Fall back per operand so one failure does not kill the join
forkJoin({ u: a$.pipe(catchError(() => of(null))), s: b$ }); // โ
// Debounce the combined output, not the individual sources
combineLatest([term$, sort$]).pipe(debounceTime(200)); // โ
// Dedupe the tuple so a no-op change does not re-run the request
combineLatest([t$, s$]).pipe(distinctUntilChanged(deepEqual)); // โ
// Make a source finite before concat consumes it
concat(interval(1000).pipe(take(3)), next$); // โ
// Use the object form of forkJoin to keep the callback readable
forkJoin({ user: u$, settings: s$ }); // โ
โ Don’t Do This:
// forkJoin over a non-completing source: dead code
forkJoin([http.get('/a'), fromEvent(document, 'click')]); // โ
// combineLatest over a chatty stream: fires per pixel
combineLatest([term$, fromEvent(document, 'mousemove')]); // โ
// concat where the first source never completes
concat(interval(1000), of('never runs')); // โ
// withLatestFrom a stream that has not emitted yet
click$.pipe(withLatestFrom(http.get('/settings'))); // โ
// Capturing state in a closure instead of sampling the stream
click$.subscribe(() => save(capturedUser)); // โ
// mergeMap over an array with no concurrency cap
from(urls).pipe(mergeMap((u) => fetch(u))); // โ
// combineLatest without startWith on a filtered stream
combineLatest([input$, filtered$]); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
forkJoin never emits | An operand never completes | Drop fromEvent/interval operands |
combineLatest never emits | An operand has not emitted once | startWith a seed value |
| Trigger clicks are lost | withLatestFrom sample is empty | startWith on the sample |
| Render loop at 60 fps | combineLatest over mousemove/scroll | withLatestFrom or debounceTime |
Second concat source never runs | First source never completed | take(n) before concatenating |
| Dashboard blank on one 404 | forkJoin error kills all operands | catchError per operand |
| Stale value in a handler | State captured at subscription time | Sample with withLatestFrom |
| Duplicate downstream calls | Tuple re-emits with equal values | distinctUntilChanged comparator |
Real-World Examples
1. Idle detection
merge(keydown$, click$, scroll$).pipe(debounceTime(60_000))
.subscribe(() => lockSession());
2. Boot sequence
concat(config$, session$, of('ready')).subscribe(startApp);
3. Filter panel state
combineLatest([term$.pipe(startWith('')), sort$.pipe(startWith('relevance'))]);
4. Parallel dashboard
forkJoin({ user: u$, settings: s$, flags: f$ }).subscribe(render);
5. Toolbar action
click$.pipe(withLatestFrom(selection$), map(([, s]) => s));
6. Failover fetch
race(http.get('/primary'), http.get('/mirror')).subscribe(render);
7. Index pairing
zip(requestIds$, responseBodies$).subscribe(([id, body]) => save(id, body));
8. Default seed
http.get('/settings').pipe(startWith(defaultSettings));
9. Safe join
forkJoin({ a: a$.pipe(catchError(() => of(null))) });
10. Tagged merge
merge(a$.pipe(map(() => ({ t: 'a' as const }))), b$.pipe(map(() => ({ t: 'b' as const }))));
Visual
merge Against concat
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ merge(A, B): BOTH SUBSCRIBED AT ONCE โ
โ โ
โ A values and B values interleave by arrival time โ
โ the output order is the network order, not the โ
โ declaration order โ
โ completes only when BOTH sources complete โ
โ โ
โ concat(A, B): B WAITS FOR A โ
โ โ
โ every A value is emitted before the first B value โ
โ B is not even subscribed until A completes โ
โ output order matches the declaration order โ
โ the price is latency: B starts after A ends โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
combineLatest Against forkJoin
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ combineLatest(A, B) โ
โ โ
โ waits for A and B to each emit once โ
โ then emits [aLatest, bLatest] on EVERY emission โ
โ from either source โ
โ completes when both complete โ
โ 1 A change + 1 B change = 2 emissions downstream โ
โ โ
โ forkJoin(A, B) โ
โ โ
โ waits for A and B to COMPLETE โ
โ then emits once with the last value of each โ
โ then completes immediately โ
โ 1 A change + 1 B change = 1 emission downstream โ
โ a source that never completes blocks output โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
withLatestFrom Against combineLatest
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ withLatestFrom: ONE TRIGGER, MANY SAMPLES โ
โ โ
โ only the SOURCE drives an emission โ
โ the others are read, never drummed โ
โ if a sampled stream has not emitted yet, the โ
โ trigger is swallowed until it has โ
โ the output completes when the source completes โ
โ โ
โ combineLatest: EVERY SOURCE DRIVES AN EMISSION โ
โ โ
โ a chatty stream (mousemove, scroll, input) makes โ
โ the combined stream chatty too โ
โ this is the most common performance bug in the โ
โ whole family: use withLatestFrom when one side is โ
โ a trigger and the others are state โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Decision Table
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PICK BY THE QUESTION YOU ARE ASKING โ
โ โ
โ all of them, in parallel, arrival order merge โ
โ one after another, declaration order concat โ
โ the latest of each, on any change combine- โ
โ Latest โ
โ the final of each, after all complete forkJoin โ
โ the current of each, when a trigger fires withLatest โ
โ the nth of each, paired by index zip โ
โ whichever answers first, then forget race โ
โ โ
โ The operator is the question. Ask what the consumer โ
โ needs, not what is convenient to import. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
merge(a, b) | interleaves all sources by arrival |
concat(a, b) | serialises; b waits for a to complete |
combineLatest([a, b]) | latest of each, on any change |
forkJoin({ a, b }) | final of each, once, on all completing |
withLatestFrom(b) | sample b when the receiver fires |
zip(a, b) | pairs the nth value of each |
race(a, b) | mirrors the first source to notify |
combineLatest precondition | every operand must emit once |
forkJoin precondition | every operand must complete |
withLatestFrom precondition | the sample must have emitted |
| Seeding operator | startWith(value) |
| Pipeable twins | mergeWith, concatWith, combineLatestWith, zipWith, raceWith |
Key takeaways:
mergeforwards by arrival;concatforwards by declaration.mergesubscribes to everything at once and is the operator for independent sources that all matter.concatsubscribes one at a time and never reaches its second source if the first never completes.combineLatestemits a full snapshot on every change. It needs one value from every operand before it can fire, sostartWithis not optional on form inputs. It is also the operator that turns a chatty stream into a busy render loop.forkJoinemits once, after everything completes. It isPromise.allfor observables and the correct operator for a dashboard or a parallel batch. A source that never completes, or completes without emitting, makes the whole thing silently dead.withLatestFrommakes one stream a trigger and the others state. It is the fix for the chatty-stream bug and for the closure-capture bug at the same time. Its one caveat is that a sample which has never emitted swallows the trigger.zipcorrelates by index;raceselects by speed.zipis for pairing request n with response n, not for coordinating timing.raceis for failover and timeouts, and it unsubscribes the losers automatically.- Every operator has a pipeable twin except
forkJoin.mergeWith,concatWith,combineLatestWith,zipWith,raceWithkeep the primary source at the head of the pipe.withLatestFromis pipeable-only because it must know which side is the trigger. - The errors are asymmetric.
merge,combineLatest,zipandforkJoinall fail the whole pipeline when one operand errors.concatfails when the active source errors and never reaches the rest. Per-operandcatchErroris the pattern that keeps a partial screen rendering.
Remember: Combining operators are chosen by the question they answer, not by the values they carry. Ask whether all sources matter (merge), whether they must run in order (concat), whether every change matters (combineLatest), whether only the final result matters (forkJoin), or whether one stream triggers a read of the others (withLatestFrom). Then check that each operand satisfies the operator’s precondition โ combineLatest needs one emission from each, forkJoin needs completion from each, withLatestFrom needs the sample to have fired at least once โ and seed with startWith wherever the precondition is not guaranteed by the source itself.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!