RXJS Custom Lettable Operators
Reminder for myself on how to work with custom lettable operator in rxjs.
Below shows takeEven as lettable operator that emits for people with even ages.
/**
* an operator that emits only even numbers
*/
const takeEven = (fn) => <T>(source: Observable<T>) =>
new Observable<T>(observer => {
let count = 0;
return source.subscribe({
next(x:any) {
if (count++ % x === 0) observer.next(x);
},
error(err) { observer.error(err); },
complete() { observer.complete(); }
})
});
const users = from([
{ name: 'Joe', age: 30 },
{ name: 'Sarah', age: 35 },
{ name: 'Edith', age: 2 },
{ name: 'Sarah-May', age: 25 }
]);
const evenAges = users.pipe(
pluck('age'),
takeEven(inp => inp)
);
// Output:
// pluck 30
// pluck 2
const subscribe = evenAges.subscribe(val => console.log('pluck', val));
`