Should I use the pipe operator if I only use one operator?
Asked Answered
G

1

6

RxJs version 5.5 introduced the pipe operator to make it easier to combine RxJs operators and to make tree shaking more efficient for these situations. My question is, should you use the pipe operator if you only intend to use one operator?

Consider the following examples:

someObservable.map(mappingLogicMethod).subscribe(x => console.log(x));

vs

someObservable.pipe(map(mappingLogicMethod)).subscribe(x => console.log(x));

In situations such as this where you only use one operator what is the most appropriate approach?

Groundmass answered 5/2, 2019 at 16:24 Comment(2)
Since RxJS 6 pipe() is the only way of using any number of operators. What you have with someObservable.map is the old "patch" style of operators that is now deprecated. github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.mdCuthburt
Basically, yes. Because the alternative will almost certainly confuse some readers: map(mappingLogicMethod)(someObservable).subscribe(x => console.log(x));Aligarh
A
3

The short answer is "You can skip the pipe, but you shouldn't" because the pipe operator is not mandatory prior to version 6.0 as mentioned by martin in the comments (so version < 6 is not a must), and if you include rxjs-compact you can use the old way of chaining operators (so you can actually use the old way everywhere up to the latest 6. version).

Lets dive a bit on the part: "Why you shouldn't use it"

Since version 5.5 the pipe operator is avaliable (but not mandatory) for usage and is usually preferred, because (back then) we all knew that in the next versions all operators will be wrapped in pipe , so you can think about that period 5.5<=6 like a migration window, to the new way.

Although we are now at version 6+ and the usage of pipe is the default behaviour, rxjs still supports the old chaining (no pipe) as long as you also install rxjs-compat.

So the answer is: If you are using rxjs 5.5+, and you want to make use of tree shaking and write readable code by the new standard (as mentioned by cartant in the comments)?

"You must always use pipe".

Algerian answered 6/2, 2019 at 8:2 Comment(4)
Apologies just to clarify: you mean "you can but shouldn't" skip using pipe, right?Amblyoscope
@Amblyoscope yes, you should always go for the pipe.Coquille
Please edit the "short answer". It's really not clear what you're referring to and can make the explanation that follows confusing. It sounds like you're saying, "you can [use the pipe operator] but you shouldn't."Bermejo
@Bermejo Is it better now?Coquille

© 2022 - 2024 — McMap. All rights reserved.