Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

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

    John LindquistJohn Lindquist
    rxjsRxJS
    ^6.0.0

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.