withLatestFrom combines the source observable with other streams and emits values calculated from the latest values of each, only when the source emits. While the similar combineLatest operator emits a new value whenever there’s a new emission from any of the input streams,
withLatestFrom emits a new value only if there’s a new emission from the guiding stream.
Just as with
combineLatest it still waits for at least one emitted value from each stream and may complete without a single emission when the guiding stream completes. It will never complete if the guiding stream doesn’t complete and will throw an error if any of the inner streams errors out.
The operator works in the following way:
- Subscribe to the guiding stream
- Subscribe to all other input observables
- When a source observable emits a value, override the value in the cache corresponding to this observable
- When a guiding stream emits a value, emit the values from each source observable as a group
- When a guiding stream completes, send the complete notification to the observer
- If any of the source observables throws an error, send the error notification to the observer.
In the diagram below you can see the
withLatestFrom operator combining two streams
B with the stream
B being the guiding stream. Every time the stream
B emits a new value the resulting sequence produces a combined value using latest value from the stream
Here is the code example that demonstrates the setup shown by the above diagram:
const a = stream('a', 500, 3); const b = stream('b', 2000, 3); b.pipe(withLatestFrom(a)).subscribe(fullObserver(operator));
And the editable demo:
UsageLink to this section
This operator can be used when you have one stream that drives emissions but also need to combine its values with latest values from other streams.