In RxJS, how can I achieve this: I have two subjects. I want an observables that combines them in this way: When both have emitted values, emit the latest of their values. Then, both need to emit at least once again, then emit their latest emitted values, etc.
Both subjects:
1 ---------- 2 ----- 3 -- 4 ---------------- 5 ------ 6 -----------------
------- a ------------------ b ------ c --------------------- d --------
Goal observable:
------- 1a ----------------- 2b ----- 3c ------------------- 4d -------
2
Answers
This can be done with the
zip
function:The term "zip" comes from zippers. The analogy is that a zipper pairs up successive teeth from each side of the zipper, so too the
zip
function pairs up successive values from the observables.https://rxjs.dev/api/index/function/zip
To achieve the desired behavior using RxJS, you can use the combineLatest operator along with the startWith operator. Here’s an example using TypeScript:
This example uses combineLatest to combine the emissions from both subjects and startWith to emit the initial values.