The withLatestFrom Operator

withLatestFrom merges the primary observable with auxiliary streams, producing values derived from the most recent emissions of each, but only when the primary source emits. This differs from combineLatest, which recalculates output on any emission from any input. With withLatestFrom, a new value is generated exclusively when the guiding observable fires.

Similar to combineLatest, this operator expects each stream to have produced at least one value. If the guiding stream completes before any combined value is formed, the output may complete empty. It also never terminates unless the guiding stream itself completes, and it propagates errors from any of the involved observables.

The operator behaves according to this sequence:

  1. Establish a subscription to the guiding stream.
  2. Establish subscriptions to all secondary input observables.
  3. Whenever one of the secondary observables emits, store that value in its corresponding cache slot.
  4. Whenever the guiding stream emits, emit the cached values from all streams together as a single group.
  5. When the guiding stream closes, send a complete notification to the observer.
  6. If any of the involved observables raises an error, forward the error notification to the observer.

The following diagram illustrates withLatestFrom pairing streams A and B, where B acts as the controlling stream. Each time B produces a value, the resulting output pairs it with the most recent value from A:

withLatestFrom operator diagram

The code sample below reproduces the setup described in the diagram:

const a = stream('a', 500, 3);
const b = stream('b', 2000, 3);

b.pipe(withLatestFrom(a)).subscribe(fullObserver(operator));

You can also experiment with the interactive version:

When to Reach for It

This operator fits scenarios where a single stream dictates the rhythm of emissions, while its output needs to be enriched with the latest state from other observables that update independently.

Further Reading