rxjs operator学习笔记
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));
一旦operators的嵌套個數變多,代碼可讀性將急劇下降:
op4()(op3()(op2()(op1()(obs))))因此有了Observable對象的pipe方法。
使用Observable的pipe方法重構之后的代碼,可讀性提高了很多:
語法:
obs.pipe(op1(),op2(),op3(),op3(), )pipe里用逗號分隔多個operator,operators名稱加上括號,括號里是具體的操作邏輯。
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的rxjs operator学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 滴滴退市后发布年报:中国出行今年3月日均
- 下一篇: 小米米家冰箱对开门 610L 冰晶白今日