Chain RxJS Operators Together with a Custom `pipe` Function using Array.reduce

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

Instead of writing complex operators, it's usually best to write simple, single-purpose operators then chain them together when necessary. The pipe function takes functions as arguments, invokes each function with the value, then passes the returned result on to the next function.

Instructor: [00:00] When you do need to make more complex operators based on existing operators used to import pipe from RXJS. This function here should return pipe and wrap those invoked operators as arguments. This is still working the same, because we've passed in map with this mapping function.

[00:23] I'm going to also pass in a filter. Pipe map, filter, and I'll say only take a value when it's less than 10. You can see now I get 3, 6, 9, 4, 8. If I comment this out, you'll see it goes back to the 3, 6, 9, 12, 15, and on. If I'll put it back in and you can see we'll only get the one's less than 10.

[00:51] You can chain these operators together to build up other operators by importing the pipe function and wrapping those operators inside of pipe. Now, pipe is really just a function. You'll see pipe is not defined, so we can implement that and say pipe is a list of functions, or an array of functions.

[01:11] Then, you remember it takes the source. We're just going to reduce over these, I'll say functions reduce. We'll write our reducing function in here and start with our source. Our reducing function has an accumulator and a current value. I'm just going to call this a function, and we'll invoke that function with the accumulator.

[01:34] It starts with the source passed in there, invoke that function on the source, get the next function, invoke with that result and go through each function doing that. I'll hit save there. It looks like it's says function reduce is not a function.

[01:49] That's because, I forgot to spread these. Spread them, so that they become an array, takes all the arguments and turns it into an array.

[01:57] Now, this is an array of functions we reduce over it and apply each function on to the source, or the result of that function being applied to the source. Now, we're back to our 3, 6, 9, 4, 8, or I can just delete this. Instead, import pipe from RXJS and get the exact same result.

J. Matthew
J. Matthew
~ 5 years ago

It's hard for me to wrap my head around why it's not necessary to do the whole source.lift routine here. My best guess is that it's because we're replacing something (pipe) out of rxjs proper, rather than an operator. What we're passing into our custom pipe is always an operator and does have to follow that pattern, so presumably our "normal" JS here is just chaining the results of each of those source.lifts together.

Markdown supported.
Become a member to join the discussionEnroll Today