With knowledge of extending Subscriber
and using source.lift
to connect a source
to a subscriber
, you can now create your own operators by writing functions that return a source.lift
call. This lesson creates a simple "multiply" operator in RxJS.
index.js:
import { from, Subscriber } from "rxjs"; import { multiply } from "./multiply"; const observable$ = from([1, 2, 3, 4, 5]); const subscriber = { next: value => { console.log(value); }, complete: () => { console.log("done"); }, error: value => { console.log(value); } }; observable$.pipe(multiply(3)).subscribe(subscriber);
multiply.js:
import { Subscriber } from "rxjs"; class MultiplySubscriber extends Subscriber { constructor(subscriber, number) { super(subscriber); this.number = number; } _next(value) { this.destination.next(value * this.number); } } export const multiply = number => source => { return source.lift({ call(sub, source) { source.subscribe(new MultiplySubscriber(sub, number)); } }); };
The most common scenario for creating custom operators is to reuse the built-in operators shipped with RxJS. You'll find yourself re-using map
, filter
, and others will solve most of the problems you come across.
import { map } from "rxjs/operators";
export const mul = number => map(v => v * number);