Home > Enterprise >  Is there a way to combine two observables that are guaranteed to be in sync?
Is there a way to combine two observables that are guaranteed to be in sync?

Time:01-28

Let's say I have two variables that I want to combine that both come from the same source observable,and I can guarantee that they're both going to be updated at the same time. To give a contrived example:

const numbers = new BehaviorSubject(1);
const numsPlus = numbers.pipe(map(x => x   1));
const numsMinus = numbers.pipe(map(x => x - 1));

numbers.next(2);
numbers.next(3);

What I want is a way to combine these such that the emissions would look like this:

[2, 0]
[3, 1]
[4, 2]

If I use combineLatest, I get this:

combineLatest(numsPlus, numsMinus)
    .subscribe(console.log);

[2, 0]
[3, 0]
[3, 1]
[4, 1]
[4, 2]

A fair thing to mention is that it might be better to do:

numbers.pipe(map(x => [x   1, x - 1]))

Let's just say that this is an older system that I didn't design, and changing it to do something different is... complicated.

CodePudding user response:

Sounds like a job for zip.

zip(numsMinus, numsPlus).subscribe(console.log)

Output:

[2, 0]
[3, 1]
[4, 2]

CodePudding user response:

An alternative solution to zip might be to combine combineLatest with a suitable debounceTime.

combineLatest([numsPlus, numsMinus]).pipe(debounceTime(<your-value>))
const numbers = interval(1000).pipe(take(5));
const numsPlus = numbers.pipe(map((x) => x   1));
const numsMinus = numbers.pipe(map((x) => x - 1));

combineLatest([numsPlus, numsMinus])
  .pipe(debounceTime(100))
  .subscribe({ next: (values) => console.log(values) });

[1,-1]
[2,0]
[3,1]
[4,2]
[5,3]

RxJS playground

  • Related