DEV Community

Discussion on: RxJS - Simplifying Complex Operator Chains

Collapse
 
sargalias profile image
Spyros Argalias

Completely agree.

I usually do this technique, and not just for RxJS. It's better to read a name of what a function does than having to parse every single thing, such as your final "real world" example.

To nitpick a little bit, I probably wouldn't have a single composed function in pipe. I would try to name the stream well and keep the functions in pipe simple. This way the name of the stream gives sufficient information and we can peek into the stream for more. However with a pipe that has a single composed function, that doesn't offer more information than the stream name itself.

Something like:

const take10EvenIntervalsMultipledBy10$ = interval(500).pipe(
    filter(isEven),
    take(10)
    map(multiplyBy10),
);
Collapse
 
averyferrante profile image
Joseph Avery Ferrante • Edited

Very good point. In my examples I'm not naming the stream variable, but that is definitely also a good source for code clarity/self commenting code.

Also I agree that only having one function in the pipe chain is probably overkill, but really wanted to drive the point home.

To expand on this idea just a bit, you can still make a function more flexible in this case (multiplyBy10 is a bit rigid) by using a factory function:

function multiplyBy(amount: number) {
  return (numberFromStream: number) => amount * numberFromStream;
}

interval(500).pipe(
  map(multiplyBy(10))
)

Thanks for providing a bit of an alternative!