0 day streak
javascript / intermediate
Snippet

Merging Streams with combineLatest

The 'combineLatest' operator merges multiple Observables into one. It emits a new array of values whenever any of the source Observables emit, provided all sources have emitted at least once. This is perfect for creating a 'View Model' object for your templates.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
export class DashboardComponent {
private user$ = this.userService.currentUser$;
private settings$ = this.settingsService.preferences$;
vm$ = combineLatest([this.user$, this.settings$]).pipe(
map(([user, settings]) => ({
username: user.name,
theme: settings.theme,
isReady: true
}))
);
}
angular
Breakdown
1
combineLatest([this.user$, this.settings$])
Waits for all Observables to emit and then combines their latest values.
2
map(([user, settings]) => ...)
Transforms the array of values into a single structured object.