Created
March 15, 2018 22:04
-
-
Save fabriciofmsilva/63085e75f53c63170cdc202ebeef76b9 to your computer and use it in GitHub Desktop.
Build Your Own Operators Easily | RxJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { interval } from 'rxjs/observable/interval'; | |
import { map, take, toArray } from 'rxjs/operators'; | |
/** | |
* an operator that takes every Nth value | |
*/ | |
const takeEveryNth = (n: number) => <T>(source: Observable<T>) => | |
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(); } | |
}) | |
}); | |
interval(1000).pipe( | |
takeEveryNth(2), | |
map(x => x + x), | |
takeEveryNth(3), | |
take(3), | |
toArray() | |
) | |
.subscribe(x => console.log(x)); | |
// [0, 12, 24] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment