3

In many articles I find that tap operator is a good way to perform side effects. My question is about a difference between performing side effects using subscribe and tap. Here are examples which are doing actually the same:

        this.store$
           .pipe(tap(x => {
               this.store = x;
           }));

        this.store$
           .subscribe(x => {
              this.store = x;
           });

Is there any difference in the performance or is there any reason to use one of these approaches?

SigGP
  • 716
  • 1
  • 11
  • 24
  • 3
    Possible duplicate of [tap() vs subscribe() to set a class property](https://stackoverflow.com/questions/49184754/tap-vs-subscribe-to-set-a-class-property) – Jameel Moideen May 23 '19 at 16:07

1 Answers1

1

In Angular context. You may have a component say MyComponent. There is a service as well for this component MyService. This service is responsible for some complex operation in MyComponent. Now you will make the subscription in the MyComponent as

$myObs.subscribe((val) => //do something );

But same data may be required in your service as well, so you define it in service as

$myObs.pipe(tap((val) => // do something with data in service));

Subscription will be done in component but using tap you can assign data member variable in your service as well.

emkay
  • 777
  • 8
  • 19