RxJS bineLatest
is deprecated and replaced with bineLatestWith
.
How do we use it when we have 3 or more streams to bine?
I've developed this example for what I thought would work.
const hello$: Observable<string> = of('hello').pipe(
bineLatestWith(of('world')),
bineLatestWith(of('!')),
map((arr) => {
const greeting = arr[0];
const subject = arr[1];
const punctuation = arr[2];
return greeting + ' - ' + subject + punctuation;
})
);
And this is the Stackblitz
Thoughts?
RxJS bineLatest
is deprecated and replaced with bineLatestWith
.
How do we use it when we have 3 or more streams to bine?
I've developed this example for what I thought would work.
const hello$: Observable<string> = of('hello').pipe(
bineLatestWith(of('world')),
bineLatestWith(of('!')),
map((arr) => {
const greeting = arr[0];
const subject = arr[1];
const punctuation = arr[2];
return greeting + ' - ' + subject + punctuation;
})
);
And this is the Stackblitz
Thoughts?
Share asked Oct 25, 2022 at 19:49 OleOle 47.5k70 gold badges238 silver badges445 bronze badges2 Answers
Reset to default 2bineLatestWith
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 bees [["hello", "world"], "!"]
where =>
is bineLatestWith
const hello$: Observable<string> = of('hello').pipe(
bineLatestWith(of('world')),
bineLatestWith(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 bines 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(
bineLatestWith(of('world')),
bineLatestWith(of('!')),
map((arr) => {
const [[greeting, subject], punctuation] = arr;
return greeting + ' - ' + subject + punctuation;
})
);
Stackblitz
If you have all the observables at hand you might also want to consider bineLatest
which will bine the latest emitted values of each observable into an array. The number of elements in that array is equal to the number of observables you put in bineLatest
:
const a$ = from(['a']);
const b$ = from(['b']);
const c$ = from(['c']);
const x$ =
bineLatest([a$, b$, c$])
.pipe(map(([a, b, c]) => `${a}.${b}.${c}`));
x$.subscribe(str => console.log(str));
<script src="https://unpkg./[email protected]/dist/bundles/rxjs.umd.min.js"></script>
<script>
const {from, bineLatest} = rxjs;
const {map} = rxjs.operators;
</script>