What is pipe for in rxJS

前端 未结 4 828
青春惊慌失措
青春惊慌失措 2020-12-02 15:07

I think I have the base concept, but there are some obscurities

So in general this is how I use an observable:



        
4条回答
  •  被撕碎了的回忆
    2020-12-02 15:29

    The pipe method

    According to original Documentation

    the pipable operator is that function take observables as a input and it returns another observable .previous observable stays unmodified.

    pipe(...fns: UnaryFunction[]): UnaryFunction
    

    Original Post

    What pipe 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.

    const { Observable } = require('rxjs/Rx')
    const { filter, map, reduce,  } = require('rxjs/operators')
    const { pipe } = require('rxjs/Rx')
    
    const filterOutWithEvens = filter(x => x % 2)
    const doubleByValue = x => map(value => value * x);
    const sumValue = reduce((acc, next) => acc + next, 0);
    const source$ = Observable.range(0, 10)
    
    source$.pipe(
      filterOutWithEvens, 
      doubleByValue(2), 
      sumValue)
      .subscribe(console.log); // 50
    

提交回复
热议问题