Search code examples
javascriptrxjsreactive-programmingrxjs5

How to emit every n-th value?


I'm using mousemove event to create an observable.

Observable.fromEvent(document, 'mousemove')

I need to emit every 10-th event. What do I do?


Solution

  • I can think of four different ways to do it:

    bufferCount()

    Observable.range(1, 55)
      .bufferCount(10)
      .map(arr => arr[arr.length - 1])
      .subscribe(val => console.log(val));
    

    windowCount()

    Observable.range(1, 55)
      .windowCount(10)
      .switchMap(window => window.takeLast(1))
      .subscribe(val => console.log(val));
    

    debounce()

    let source = Observable.range(1, 55).publish();
    
    source
      .debounce(val => debounceNotifier)
      .subscribe(val => console.log(val));
    
    let debounceNotifier = source
      .bufferCount(10)
      .publish();
    debounceNotifier.connect();
    
    source.connect();
    

    scan()

    Observable.range(1, 55)
      .scan((acc, val) => {
        if (acc.length === 10) {
          acc = [];
        }
        acc.push(val);
        return acc;
      }, [])
      .filter(acc => acc.length === 10)
      .map(acc => acc[acc.length - 1])
      .subscribe(val => console.log(val));
    

    However, when using scan() it'll will discard the last value 55.

    See demo for all of them: https://jsbin.com/yagayot/14/edit?js,console