John Abraham
John Abraham

Reputation: 18771

How to defer the emission from an Observable based on another event stream?

What would be the operator to make an observable from an array but only emit the next observable value based on the change/count of another event stream, let's say a click?

const scroller$ = Rx.Observable.of(1,2,3,4);
Rx.Observable.fromEvent(document, 'click'); // need help here
scroller$.subscribe(console.log) 

// click // 1

// click // 2

// click // 3

// click // 4

Upvotes: 0

Views: 131

Answers (1)

cartant
cartant

Reputation: 58400

You could use zip to do that:

const scroller$ = Rx.Observable.of(1, 2, 3, 4);
scroller$.zip(
  Rx.Observable.fromEvent(document, 'click'),
  (value, event) => value // Specify a projection function to ignore the event
).subscribe(console.log);

The documentation for zip is here, but it's ... a work in progress.

Basically, zip combines the values emitted by the input observables in lock-step. So when the first event is emitted, it will be combined and emitted with the first value from scroller$ and nothing further will be emitted until the second event occurs, etc.

zip can be passed a function to project the combined values, so if you are interested only in the value - and not the event - you can use a projection function to ignore the event.

Upvotes: 1

Related Questions