Crocsx
Crocsx

Reputation: 7589

zip 2 observable everytime one of them emit

I have the following

const timer1 = interval(1000).pipe(take(10));
const timer2 = interval(2000).pipe(take(6));
const merged = merge(timer1, timer2);
merged.subscribe(x => console.log(x));

Now this will only provide the value of the latest emitting observable.

I would like that, when one emit, I get the new value, and the latest from the other one.

I tried to use zip but it will not use the latest. Check the screenshot below for the missing value I wish to have. How can I achieve this ?

Join, would work, but join do not emit if the same observable emitted twice before the other one emitted a value.

enter image description here

Upvotes: 3

Views: 799

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

You are looking for combineLatest.

combineLatest will emit whenever either of the source observables emit. Note: it will not emit for the first time until each observable has emitted at least once.

combineLatest marbles

So with your example, it could look like this (StackBlitz):

const timer1 = interval(1000).pipe(take(10));
const timer2 = interval(2000).pipe(take(6));
const merged = combineLatest([timer1, timer2]);

merged.subscribe(([one, two]) => console.log(`${one}-${two}`));

Upvotes: 2

Related Questions