【转】Deep dive into pipe function in RxJS
原文: https://codewithstyle.info/deep-dive-pipe-function-rxjs/
------------------------------------------------------------
Version 5 of RxJS introduced the concept of lettable (also known as pipeable) operators. Version 6 went one step further and deprecated the old way of calling operators (method chaining). You might have already used the pipe function. But do you really understand what it does?
Composing functions
RxJS is often called a functional-reactive programming library. It should not come as a surprise that you will find many functional programming inspirations in it. One of them is the pipe function. Take a look at the below piece of code:
const getElement = |
The logElementValue function takes an id and logs to the console the value of the element with provided id. Can you see a pattern in this function’s implementation? Firstly, it calls getElement with id and stores the result in el. Next, the result is passed to getValue which produces a new result, el. Finally, el is passed to console.log. What this function does is simply taking the result of a function and passing it as an argument to another function. Is there a better, more concise way to implement this function? Let’s say we just have two functions (getElement and getValue). We will implement a generic function called compose that will pass the result of getElement to getValue.
const compose = (f, g) => x => g(f(x)); |
The definition is very simple but may take a moment to parse. We’ve defined a function that takes two functions f and g (that would be getElement and getValue in our case) and returns a new function. This new function will take an argument, pass it to f and then pass the result to g. That’s exactly what we need! Now I can rewrite logElementValue:
function logElementValue(id) {
|
How about more than two functions?
But, wait! Once we have the result of calling getValueFromId we immediately pass it to console.log. So it’s the same pattern here. We could write it like this:
function logElementValue(id) {
|
But life would be much simpler if compose could take any number of functions. Can we do this? Sure:
const composeMany = (...args) => args.reduce(compose); |
Another brain teaser! composeMany takes any number of functions. They are stored in args array. We reduce over args composing every function with the result of composing previous functions. Anyway, the results is a function that takes any number of functions and will pass the result of N-th function to (N+1)-th function. But what have we achieved by that?
function logElementValue(id) {
|
Which can be simplified even more:
const logElementValue = composeMany(getElement, getValue, console.log); |
Isn’t that cool? We have significantly simplified the code. It’s now very clear what logElementValue does. And by the way - composeMany is just a name a came up with. The official name is pipe!
const logElementValue = pipe(getElement, getValue, console.log); |
Back to RxJS
Let’s take an example of pipe usage in RxJS.
number$.pipe( |
We can also write it in a different way:
const { pipe } = rxjs;
const transformNumbers = pipe(
|
And the result is exactly the same! As you can see, the pipe function in RxJS behaves in exactly the same way that the pipe function that we’ve defined in the first part of the article. It takes a number of functions and composes them by passing the result of a function as an argument to another function. You might say that this is different than the previous example because here we’re invoking map and filter and not simply passing them. Actually, both map and filter will return functions. We’re not composing map and filter themselves but rather the functions returned by invoking them. You can check out how RxJS implements pipe function here.
Pipeline operator
Our function is such a useful concept that it might be added as a separate operator to the JavaScript language! It would mean that the example from the previous article can be written in an even simpler way:
const logElementValue = getElement |> getValue |> console.log; |
You can see the details of the proposal here.
Summary
I hope this article helped you understand what pipe function is all about. You should now feel more comfortable using it! The fact that RxJS migrated from the traditional, object-oriented approach of applying operators to the pipeline approach shows how strong the influence of functional programming is nowadays. I think that’s great! Let me know in comments if you prefer pipe function to traditional method chaining.
【转】Deep dive into pipe function in RxJS的更多相关文章
- [RxJS] Chain RxJS Operators Together with a Custom `pipe` Function using Array.reduce
Instead of writing complex operators, it's usually best to write simple, single-purpose operators th ...
- X64 Deep Dive
zhuan http://www.codemachine.com/article_x64deepdive.html X64 Deep Dive This tutorial discusses some ...
- 《Docker Deep Dive》Note - Docker 引擎
<Docker Deep Dive>Note Docker 引擎 1. 概览 graph TB A(Docker client) --- B(daemon) subgraph Docker ...
- Deep Dive into Neo4j 3.5 Full Text Search
In this blog we will go over the Full Text Search capabilities available in the latest major release ...
- Deep Dive into Spark SQL’s Catalyst Optimizer(中英双语)
文章标题 Deep Dive into Spark SQL’s Catalyst Optimizer 作者介绍 Michael Armbrust, Yin Huai, Cheng Liang, Rey ...
- 《Docker Deep Dive》Note - 纵观 Docker
<Docker Deep Dive>Note 由于GFW的隔离,国内拉取镜像会报TLS handshake timeout的错误:需要配置 registry-mirrors 为国内源解决这 ...
- 重磅解读:K8s Cluster Autoscaler模块及对应华为云插件Deep Dive
摘要:本文将解密K8s Cluster Autoscaler模块的架构和代码的Deep Dive,及K8s Cluster Autoscaler 华为云插件. 背景信息 基于业务团队(Cloud BU ...
- vue3 deep dive
vue3 deep dive vue core vnode vue core render / mount / patch refs https://www.vuemastery.com/course ...
- A Deep Dive Into Draggable and DragTarget in Flutter
https://medium.com/flutter-community/a-deep-dive-into-draggable-and-dragtarget-in-flutter-487919f6f1 ...
随机推荐
- 面试之leetcode链表
1 数组 (1)数组的插入 如果是插入到最后,那么不用移动O(1),如果插入位置在中间为O(n).所以最好O(1),最坏O(N),平均O(N),为了插入能达到O(1),插入O(1).引入了链表 2 链 ...
- IDEA 自定义代码模板
IDEA 自定义代码模板操作步骤:
- [转帖]推荐一款比 Find 快 10 倍的搜索工具 FD
推荐一款比 Find 快 10 倍的搜索工具 FD https://www.hi-linux.com/posts/15017.html 试了下 很好用呢. Posted by Mike on 2018 ...
- Apache Kafka Producer For Beginners
在我们上一篇Kafka教程中,我们讨论了Kafka Cluster.今天,我们将通过示例讨论Kafka Producer.此外,我们将看到KafkaProducer API和Producer API. ...
- xorm -Find方法实例
查询多条数据使用Find方法,Find方法的第一个参数为slice的指针或Map指针,即为查询后返回的结果,第二个参数可选,为查询的条件struct的指针. package main import ( ...
- AS3放大镜工具类
package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Display ...
- vue3 template refs dom的引用、组件的引用、获取子组件的值
介绍 通过 ref() 还可以引用页面上的元素或组件. DOM 的引用 <template> <div> <h3 ref="h3Ref">Tem ...
- BZOJ4141 THUSC2013 魔塔 贪心
没得传送门 考虑当\(Atk\)增大时,\(Def\)一定越来越没用,因为回合数在变少.所以考虑从小到大枚举\(Atk\)然后双指针计算. 设\(f_i(x)\)表示在\(Atk = i\)时,\(D ...
- c# $和@ 简化字符串格式化拼接
int age=18; Console.WriteLine($"XiaoMing is \"{age}\" {{ years}} old"); Console. ...
- 入门Docker,你要下载什么?注册什么?
此随笔根据前人经验改编并亲自实践.遇到问题提供出相应解决方法. 入门Docker,你要下载什么?注册什么? Docker.app你肯定是要下载的!此教程应用于MAC系统PC不保证适用 Docker f ...