sdfsd
sdfsd

Reputation: 1213

What are the advantages/disadvantages of performing operations in pipe() rather than directly in subscribe() method?

I'm new to Angular and I'm filtering the user with the id same as in the JWT payload.

I can do this in the subscribe() of the Observable like this:

  this.route.data.subscribe((data) => {
      this.users = data.users.filter((u: User) => u.id !== +this.authService.decodedToken.nameid);
  });

I also can do this in the pipe() method like:

this.route.data
  .pipe(map(data => data.users.filter((u: User) => u.id !== +this.authService.decodedToken.nameid)))
  .subscribe((data) => {
    this.users = data;
  });

Resolver code (probably irrelevant to the question):

  resolve(route: ActivatedRouteSnapshot): Observable<User[]> {
        return this.userService.getUsers().pipe(
            catchError(error => {
                this.alertify.error('Problem retrieving data');
                this.router.navigate(['/home']);
                return of(null);
            })
        );
    }

Now why should I use the pipe() method rather than filtering directly in the subscribe() method are there any advantages or disadvantages of using pipe() in this scenario? Which of the two is the conventional Angular way of doing this?

I would think that the pipe() would be a little bit slower, since it first maps and then filters.

Upvotes: 1

Views: 1581

Answers (2)

Tarun1704
Tarun1704

Reputation: 191

With pipable operators now, you are doing declarative programming. if we do everything in subscribe, there are some pitfalls to it

  • Merging with another observable becomes difficult.
  • What if you want to get value from observable1 and pass it to observable2, will you do mergeMap or subscribe inside another subscription (never do that).
  • All your logic is now inside one function, difficult to read.

When u write pipable operators

  1. Each function performs one specific logic.
  2. Separation of concerns
  3. you will have to subscribe only once (to the end result)
  4. Code looks neat

Look at the example

const obs1$ = of(1,2,3,4,5);
obs1$.pipe(filter(val => val%2 === 0), map(val => val*2).subscribe(finalValue => console.log(value)

writing all this inside subscribe will surly look crappy! hope this helps

Upvotes: 3

Adrian Brand
Adrian Brand

Reputation: 21658

It creates an observable that emits the value you want. In Angular we often use the async pipe so we don't have to manage subscriptions so map is useful in creating and observe where the data that comes into the async pipe is the data we want to use in the template

users$ = this.route.data
  .pipe(map(data => data.users.filter((u: User) => u.id !== +this.authService.decodedToken.nameid)));

and use the async pipe

<ng-container *ngIf="users$ | async as users">
  {{ users | json }} users here is updated each time users$ emits a value
</ng-container>

The async pipe manages the subscriptions for us and we don't need to wory about unsubscribing.

This is just the tip of the iceberg with RxJs and pipes. You really should stop learning Angular for a bit a come back once you have a good understanding of the RxJs fundamentals. It will really change the way you build Angular components.

Upvotes: 1

Related Questions