skip to Main Content

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


  1. This can be done with the zip function:

    import { zip } from 'rxjs'
    
    zip(subject1$, subject2$)
      .subscribe(([val1, val2]) => {
        console.log(`${val1}${val2}`);
      });
    

    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

    Login or Signup to reply.
  2. To achieve the desired behavior using RxJS, you can use the combineLatest operator along with the startWith operator. Here’s an example using TypeScript:

    private subject1 = new BehaviorSubject<number>(1);
    private subject2 = new BehaviorSubject<string>('a');
    
    
    combineLatest([
          this.subject1.pipe(startWith(this.subject1.value)),
          this.subject2.pipe(startWith(this.subject2.value)),
        ]).subscribe(([value1, value2]) => `${value1}${value2}`)

    This example uses combineLatest to combine the emissions from both subjects and startWith to emit the initial values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search