While it's great to use the RxJS built-in operators, it's also important to realize you now have the knowledge to write them by yourself if needed. The map
operator turns out to be a simple MapSubscriber
which takes a function and applies it to the value passed to next
.
map.js:
import { Subscriber } from "rxjs"; class MapSubscriber extends Subscriber { constructor(sub, fn) { super(sub); this.fn = fn; } _next(value) { this.destination.next(this.fn(value)); } } export const map = fn => source => source.lift({ call(sub, source) { source.subscribe(new MapSubscriber(sub, fn)); } });
multiply.js:
import { map } from "./map"; export const mul = number => map(v => v * number);
index.js:
import { from, Subscriber } from "rxjs"; import { multiply, mul } 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(mul(3)).subscribe(subscriber); observable$.pipe(mul(4)).subscribe(subscriber);