简体   繁体   English

如何发出每个第n个值?

[英]How to emit every n-th value?

I'm using mousemove event to create an observable. 我正在使用mousemove事件来创建一个observable。

Observable.fromEvent(document, 'mousemove')

I need to emit every 10-th event. 我需要每10次发射一次。 What do I do? 我该怎么办?

I can think of four different ways to do it: 我可以想到四种不同的方法:

bufferCount() bufferCount()

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

windowCount() 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 . 但是,当使用scan() ,它将丢弃最后一个值55

See demo for all of them: https://jsbin.com/yagayot/14/edit?js,console 查看所有这些的演示: https//jsbin.com/yagayot/14/edit?js,console

Here's an even simpler and considerably faster approach, which I tested with RxJS 6: 这是一个更简单,更快速的方法,我用RxJS 6测试过:

range(1, 10000000)
  .pipe(
    filter(function(value, index) { 
      return index % 10 === 0; 
    }),
  );

This code is twice as fast as the bufferCount and windowCount approaches in the other answer: https://jsperf.com/observable-nth/1 在另一个答案中,此代码的速度是bufferCountwindowCount接近的两倍: https//jsperf.com/observable-nth/1

This is likely because the filter operator uses a simple counter, instead of having to keep a buffer of the last n elements. 这可能是因为filter运算符使用简单的计数器,而不是必须保留最后n元素的缓冲区。 I assume this is even faster when n is larger or the elements themselves are bigger. 我认为当n更大或元素本身更大时,这甚至更快。 With RxJS 6, you can also easily make this into your own custom operator: 使用RxJS 6,您还可以轻松地将其转换为您自己的自定义运算符:

const takeEveryNth = (n: number) => filter((value, index) => index % n === 0);
// usage: rxjs.range(1, 10000000).pipe(takeEveryNth(10));

It is also the code used in the official docs explaining how to create custom operators: https://github.com/ReactiveX/rxjs/blob/6.2.2/doc/pipeable-operators.md 它也是官方文档中使用的代码,解释了如何创建自定义运算符: https//github.com/ReactiveX/rxjs/blob/6.2.2/doc/pipeable-operators.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM