tap() vs subscribe() to set a class property
tap
is useful when you have the observable separated from its subscriber. If you have a class that exposes an observable, you can use tap
to implement side effects that this class needs to be executed when someone is listening to the observable. In the other side, when you subscribe to it from another class, you can implement side effects from the subscriber's point of view, using subscribe
.
Class with the observable:
public dummyObservable: Observable<number> = from([1, 2, 3, 4, 5]).pipe(
// Side effects, executed every time I emit a value
// I don't know which side effects implements who subscribes to me
tap( n => console.log("I'm emitting this value:", n) )
);
Class with the subscription:
ngOnInit(): void {
this.dummyService.dummyObservable.subscribe(
// Side effects, executed every time I receive a value
// I don't know which side effects implements the observable
data => console.log("I'm receiving this value: ", data)
);
}
Good question. In the source code for the tap
operator, this comment pretty much sums it up:
This operator is useful for debugging your Observables for the correct values or performing other side effects.
Note: this is different to asubscribe
on the Observable. If the Observable returned bydo
is not subscribed, the side effects specified by the Observer will never happen.do
therefore simply spies on existing execution, it does not trigger an execution to happen likesubscribe
does.
Any side effect you can run in a tap
can probably also be put in the subscribe
block. The subscribe
indicates your intent to actively use the source value since it's saying "when this observable emits, I want to save it's value in the applicants
variable". The tap
operator is mostly there for debugging, but it can be used to run side effects.
In general, favor the subscribe
block for running side effects, use tap
for debugging, but be aware that tap
can do more if you need it to.