RxJS 5.5, piping all the things

From https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44

 

 

RxJS 5.5, piping all the things

With RxJS 5.5 came the introduction of pipeable, or “lettable”, operators.

Those operators are pure functions that can be used as standalone operators instead of methods on an observable.

They’re lightweight, will make your code easily re-usable and can decrease your overall build size.


Previously, we used to do the following for things like filter , mapscan , …

Operators as pure functions

Whereas now all those operators are available as pure functions under rxjs/operators.

What does that mean? That means it’s really easy to build custom operators !

Let’s say I know that I’m going to re-use this filter, well, with lettable operators I can just do this:

So now we want a way to use those operators, how could we do that?

Well, we said those operators are “lettable” that means we can use them by calling the let method on an observable:

And if we want to chain multiple lettable operators we can keep dot chaining:

The pipe method

All this looks cool but its still very verbose. Well, thanks to RxJS 5.5 observables now have a pipe method available on the instances allowing you to clean up the code above by calling pipe with all our pure functions operators:

What does that mean? That means that any operators you previously used on the instance of observable are available as pure functions under rxjs/operators. This makes building a composition of operators or re-using operators becomes really easy, without having to resort to all sorts of programming gymnastics where you have to create a custom observable extending Observable, then overwrite lift just to make your own custom thing.


The Pipe util

Alright, hold up, “but what if I want to re-use this logic in different places ? Do I build a custom .pipe with my operators?” you’ll ask me. Well you don’t even have to do that because, lucky us, RxJS also comes with a standalone pipe utility !

Meaning we can easily compose a bunch of pure function operators and pass them as a single operator to an observable!

Conclusion

With those tools in hand, you can write RxJS code that is much more re-usable by just piping your (pure functions) operators together and easily re-use shared logic.

For more information, check out: https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md


Shameless plug:

You can find me on twitter and github ! Feel free to share this post and clap it away.

You can find more information about  Hackages  on our  website . We’re a community driven company that offers  high level training  on the latests frameworks and technologies around JavaScript. We also love to contribute to open source  and to organise free community events all around Europe! Check our upcoming events near you at https://hackages.io .

猜你喜欢

转载自blog.csdn.net/welchlam/article/details/81237157
5.5
ALL