创建一个文件夹,例如rxjs-test
mkdir rxjs-test
cd rxjs-test
创建一个node工程
npm init
加入rxjs
yarn add rxjs
或者
npm install rxjs
创建index.js文件
touch index.js
const { interval, Observable } = require("rxjs");
const { filter, map, take, toArray } = require("rxjs/operators");
/**
* 取每第N个值的操作符
*/
/* tslint:disable */
const takeEveryNth = (n) => (source) =>
new Observable(observer => {
let count = 0;
return source.subscribe({
next(x) {
if (count++ % n === 0) { observer.next(x); }
},
error(err) { observer.error(err); },
complete() { observer.complete(); }
});
});
/**
* 还可以使用现有的操作符
*/
const takeEveryNthSimple = (n) => (source) =>
source.pipe(filter((value, index) => index % n === 0));
/**
* 因为 pipeable 操作符返回的是函数,还可以进一步简化
*/
const takeEveryNthSimplest = (n) => filter((value, index) => index % n === 0);
interval(100).pipe(
takeEveryNth(2),
map(x => x + x),
takeEveryNthSimple(3),
map(x => x * x),
takeEveryNthSimplest(4),
take(3),
toArray()
).subscribe(x => console.log(x));
运行代码
node index.js