Skip to content
jshacks.dev
Async

The RxJS withLatestFrom Operator Explained With Examples

Learn how the RxJS withLatestFrom operator samples other streams when the main one emits, and how it differs from combineLatest and zip.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ and Redis logos.

Some events carry no data of their own. A "Save" click says that something should happen, but the form values live elsewhere, in other streams that have been changing for minutes. You want the click to trigger the work and to read the current state at that moment, without the state changes triggering anything themselves. withLatestFrom does exactly that. The main stream decides when output happens, and the other streams are only looked at, never listened to for timing. This post explains withLatestFrom in RxJS 7 with printed output, shows the silent-start rule that drops early values, compares it with combineLatest and zip, and covers the typical click-plus-state pattern and its pitfalls.

What it does

withLatestFrom(other$) subscribes to other$ and remembers its latest value. Each time the source emits, the operator emits an array of the source value and the remembered value. Emissions from other$ alone produce no output.

JavaScript
import { Subject } from "rxjs";
import { withLatestFrom } from "rxjs/operators";

const clicks$ = new Subject();
const text$ = new Subject();

clicks$.pipe(withLatestFrom(text$)).subscribe(([click, text]) =>
  console.log(`click ${click} with text "${text}"`)
);

text$.next("h");
text$.next("he");
clicks$.next(1);
text$.next("hel");
text$.next("hell");
clicks$.next(2);
Text
click 1 with text "he"
click 2 with text "hell"

Four text values arrived, and two clicks produced two outputs. Typing never triggered anything. Each click picked up whatever the text was at that instant.

The silent-start rule

If the source emits before other$ has emitted anything, the source value is dropped. There is no remembered value to pair it with.

JavaScript
import { Subject } from "rxjs";
import { withLatestFrom } from "rxjs/operators";

const clicks$ = new Subject();
const text$ = new Subject();

clicks$.pipe(withLatestFrom(text$)).subscribe(([c, t]) => console.log(c, t));

clicks$.next("early click");
text$.next("first text");
clicks$.next("later click");
Text
later click first text

The early click is lost. This is the same trap as combineLatest not starting, with a worse effect: instead of waiting, the operator discards the main events. Give the sampled stream an initial value when this matters.

JavaScript
import { Subject } from "rxjs";
import { startWith, withLatestFrom } from "rxjs/operators";

const clicks$ = new Subject();
const text$ = new Subject();

clicks$
  .pipe(withLatestFrom(text$.pipe(startWith(""))))
  .subscribe(([c, t]) => console.log(c, JSON.stringify(t)));

clicks$.next("early click");
Text
early click ""

Several streams

Pass several observables, and the output array gets one extra element for each.

JavaScript
import { BehaviorSubject, Subject } from "rxjs";
import { withLatestFrom } from "rxjs/operators";

const submit$ = new Subject();
const name$ = new BehaviorSubject("Ada");
const age$ = new BehaviorSubject(36);

submit$.pipe(withLatestFrom(name$, age$)).subscribe(([_, name, age]) =>
  console.log({ name, age })
);

age$.next(37);
submit$.next();
Text
{ name: 'Ada', age: 37 }

In RxJS 7 you can also pass an array, as in withLatestFrom([name$, age$]), which keeps the same output shape.

withLatestFrom versus combineLatest

The difference is who triggers output.

JavaScript
import { Subject, combineLatest } from "rxjs";
import { withLatestFrom } from "rxjs/operators";

const a$ = new Subject();
const b$ = new Subject();

a$.pipe(withLatestFrom(b$)).subscribe((v) => console.log("withLatestFrom", v));
combineLatest([a$, b$]).subscribe((v) => console.log("combineLatest", v));

b$.next("b1");
a$.next("a1");
b$.next("b2");
a$.next("a2");
Text
withLatestFrom [ 'a1', 'b1' ]
combineLatest [ 'a1', 'b1' ]
combineLatest [ 'a1', 'b2' ]
withLatestFrom [ 'a2', 'b2' ]
combineLatest [ 'a2', 'b2' ]

When b$ emitted b2, combineLatest produced a pair and withLatestFrom produced nothing. If your handler should run only when the user does something, withLatestFrom avoids spurious runs triggered by background state.

withLatestFrom versus zip

zip pairs values by position, the first with the first, the second with the second. It waits for both. That makes it useful for lockstep streams and wrong for "action plus current state".

JavaScript
import { of, zip } from "rxjs";

zip(of("a1", "a2", "a3"), of("b1", "b2")).subscribe((v) => console.log(v));
Text
[ 'a1', 'b1' ]
[ 'a2', 'b2' ]

The third value of the first stream had no partner, so zip completed without it.

The save-button pattern

JavaScript
import { BehaviorSubject, Subject, of } from "rxjs";
import { concatMap, delay, withLatestFrom } from "rxjs/operators";

const saveClicks$ = new Subject();
const form$ = new BehaviorSubject({ title: "", body: "" });

saveClicks$
  .pipe(
    withLatestFrom(form$),
    concatMap(([, form]) =>
      of(`saved "${form.title}"`).pipe(delay(10))
    )
  )
  .subscribe(console.log);

form$.next({ title: "Draft", body: "..." });
saveClicks$.next();
form$.next({ title: "Final", body: "..." });
saveClicks$.next();
Text
saved "Draft"
saved "Final"

Each save used the form as it was at click time. Because withLatestFrom is sampled before concatMap, a later edit cannot change a save that has already started.

State stores and selected values

A common use is reading the current state in an effect. An action stream triggers it, and withLatestFrom(store.select(...)) supplies the data. In NgRx effects this is the standard way to read the store, since reading it in switchMap with select would subscribe repeatedly.

Timing detail: same-tick emissions

If the source and the sampled stream emit in the same synchronous run, the order of subscription matters. The operator subscribes to the other streams first, so a value emitted by the other stream while subscribing is captured before the source's first value.

JavaScript
import { of } from "rxjs";
import { withLatestFrom } from "rxjs/operators";

of("click").pipe(withLatestFrom(of("state"))).subscribe(console.log);
Text
[ 'click', 'state' ]

That is why synchronous cold sources work as the sampled input without any additional setup.

Common mistakes

Expecting updates from the sampled stream to emit. They never do. Use combineLatest if they should.

Losing early events. Without an initial value in the sampled stream, early source values are dropped. Use startWith or a BehaviorSubject.

Sampling after an async operator. If you sample after switchMap, you read the state at response time, not at click time. Place withLatestFrom first.

Using it for pairing by position. That is zip.

Forgetting completion. The output completes when the source completes, and completion of the sampled stream does not end it.

Avoiding stale reads

The operator reads the sampled value at the moment the source emits, and that is a feature, but it also means the value can be older than you expect when the source is slow to arrive. Imagine a click handler that uses withLatestFrom(form$) after a debounceTime(300). The sampled form value is the one at the time the debounced click is emitted, three hundred milliseconds after the user pressed the button, and any edits made in that time are included. If the intent was to save what the user saw at the moment of the click, sample before the delay, by placing withLatestFrom ahead of debounceTime in the pipe.

State stores and selectors

In effect-style architectures, an action triggers a side effect that needs some part of the state. Reading the state inside the effect with withLatestFrom(store.select(selector)) keeps the effect declarative and avoids a subscription inside a subscription. The same pattern applies to configuration or the current user: any slowly changing value that a fast event needs for context belongs in withLatestFrom, not in combineLatest, because you do not want a change in that context to cause an extra run of the effect.

The cost of subscribing to the sampled stream

withLatestFrom subscribes to the other observables as soon as the output is subscribed, and keeps them subscribed until the output completes. If a sampled stream is expensive to run, such as a request on every subscription, you are paying for it whether or not the source ever emits. Share such streams with shareReplay({ bufferSize: 1, refCount: true }) so that they are cheap to sample and clean up with the rest.

Testing the timing

A marble diagram makes the sampling rule visible. With a source of ---a---b and a sampled stream of x--y----, the output is ---a---b paired with x and y respectively. The sampled stream's own emissions produce no output, and the first source value is only kept if the sampled stream has already emitted. Writing that down once in a test documents the behavior for the next developer far better than a comment does.

Summary of when to sample

Sampling is the right model whenever one stream carries the question and others carry the context. Clicks ask for an action, and the form, the user and the settings are context. Messages ask for processing, and the current configuration is context. Timer ticks ask for a poll, and the current filter is context. In each case, a change in the context should not cause the action by itself, and withLatestFrom states that rule in the code, where a future reader can see it without reading the comments.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.