Create a Reusable Operator from Scratch in RxJS

Share this video with your friends

Send Tweet

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.

Karl Purkhardt
Karl Purkhardt
~ 6 years ago

Fantastic course John, I'm really enjoying it. You should be a Quokka.js affiliate too, I'm now about to purchase a license after seeing it's true potential!

J. Matthew
J. Matthew
~ 5 years ago

This is really neat. It took me a little while to wrap my brain around why the multiply function itself needs to return a function, rather than simply making number a second argument, after source. The reason is that what you pass into pipe needs to be a function that just takes the source argument, which is what pipe supplies. Consequently, if you want to pass additional arguments, you have to write a wrapper function that takes those additional arguments, then returns a function that uses those arguments internally, but just takes the source argument when called. Then when you call that wrapper function inside the pipe call, it resolves to what pipe expects.

If you did want to just make number a second argument, you could do it this way instead:

observable$.pipe(source => multiply(source, 4)).subscribe(subscriber);

Which amounts to the same thing (but arguably doesn't look as clean).