Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS / Angular Observables use 1 or multiple pipes?

Having the following (just a quick example):

observable.pipe(map( s => s.anything ))
          .pipe(filter(t => t > 5))
          .pipe(map( t => t+5))
          .subscribe( XXX )

Why should I use 1 pipe instead?

    observable.pipe(
                   map( s => s.anything ), filter(t => t > 5),map( t => t+5))
              .subscribe( XXX )

To me, the code is more nice and readable in the first case. But no idea if that affects the behaviour anyway.

like image 759
user2992476 Avatar asked May 07 '19 08:05

user2992476


People also ask

Why we use pipe in Observable?

The pipe method of the Angular Observable is used to chain multiple operators together. We can use the pipe as a standalone method, which helps us to reuse it at multiple places or as an instance method.

Does pipe subscribe to Observable?

Async pipelinkThe AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted.

Does pipe create a new Observable?

A Pipeable Operator is essentially a pure function which takes one Observable as input and generates another Observable as output. Subscribing to the output Observable will also subscribe to the input Observable.


1 Answers

You should use a single pipe for that purpose. Having multiple pipes will serve no purpose or benefit, as the usage of pipes is to combine RxJS functional operators into a single chain.

In order to make it more readable, you can do something like this, instead of having all the operators on 1 single line of code.

observable
  .pipe(
    map(s => s.anything ),
    filter(t => t > 5),
    map(t => t+5)
  ).subscribe(res => {
    // do the rest
});

The official Angular guide has a good summary on the usage of pipes and other operators. You may read up more about it over here. You should read up about pipeable operators over here as well.

like image 78
wentjun Avatar answered Oct 27 '22 09:10

wentjun