zl程序教程

您现在的位置是:首页 >  工具

当前栏目

rxjs operator学习笔记

笔记学习 Rxjs Operator
2023-09-14 09:04:03 时间

Pipeable Operators are the kind that can be piped to Observables using the syntax observableInstance.pipe(operator()). These include, filter(…), and mergeMap(…). When called, they do not change the existing Observable instance. Instead, they return a new Observable, whose subscription logic is based on the first Observable.
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified.

operator就是函数式编程世界里的一等公民,接收一个Observable作为输入,返回另一个新的Observable对象。

Operators are the essential pieces that allow complex asynchronous code to be easily composed in a declarative manner.

借助operator,我们可以使用一种声明式的方式来进行异步编程。

map((x: number) => x * x)(of(1, 2, 3)).subscribe((v) => console.log(`value: ${v}`));

上面这个例子里map的左右括号很有迷惑性,乍一看很像函数调用的括号,实际上括号内包含的是箭头函数的函数体。

下图这对括号才是真正函数调用的括号。

let a = (x: number) => x * x;
    let b = map(a);

    let c = of(1,2,3);
    // c.subscribe((data) => console.log('value: ' + data ));
    let d = b(c);
    d.subscribe((data) => console.log('diablo: ' + data));


 let a = (x: number) => x * x;
    let b = map(a);

    let c = of(1,2,3);
    // c.subscribe((data) => console.log('value: ' + data ));
    let d = b(c);
    d.subscribe((data) => console.log('diablo: ' + data));

    let e = (x: number) => x + x;
    let f = map(e);

    let g = f(d);
    g.subscribe((data) => console.log('baal: ' + data));

一旦operators的嵌套个数变多,代码可读性将急剧下降:

op4()(op3()(op2()(op1()(obs))))

因此有了Observable对象的pipe方法。

使用Observable的pipe方法重构之后的代码,可读性提高了很多:

语法:

obs.pipe(
  op1(),
  op2(),
  op3(),
  op3(),
)

pipe里用逗号分隔多个operator,operators名称加上括号,括号里是具体的操作逻辑。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":