RxJS combineLatest
is deprecated and replaced with combineLatestWith
.
How do we use it when we have 3 or more streams to combine?
I've developed this example for what I thought would work.
const hello$: Observable<string> = of('hello').pipe(
combineLatestWith(of('world')),
combineLatestWith(of('!')),
map((arr) => {
const greeting = arr[0];
const subject = arr[1];
const punctuation = arr[2];
return greeting ' - ' subject punctuation;
})
);
Thoughts?
CodePudding user response:
combineLatestWith
joins the observable with the given one in an array (say cons). Imagine it like so:
"hello"
=>"world"
=["hello", "world"]
["hello", "world"]
=>"!"
=[["hello", "world"], "!"]
so arr becomes [["hello", "world"], "!"]
where =>
is combineLatestWith
const hello$: Observable<string> = of('hello').pipe(
combineLatestWith(of('world')),
combineLatestWith(of('!')),
map((arr) => {
const first = arr[0];
const greeting = first[0]
const subject = first[1];
const punctuation = arr[1];
return greeting ' - ' subject punctuation;
})
);
From docs: Create an observable that combines the latest values from all passed observables and the source into arrays and emits them.
The code can look nicer with destructuring, like so:
const hello$: Observable<string> = of('hello').pipe(
combineLatestWith(of('world')),
combineLatestWith(of('!')),
map((arr) => {
const [[greeting, subject], punctuation] = arr;
return greeting ' - ' subject punctuation;
})
);