In my last post, I covered how we can define multiple callback functions when subscribing to an Observable (next
, error
, complete
). I mentioned that those callbacks are available when we call the subscribe()
method, which goes against our philosophy of avoiding subscriptions as much as possible because they can lead to memory leaks.
In previous newsletters, I covered how the tap
operator can help avoid subscriptions by “spying” on an Observable.
Well, tap
is a simple gift that keeps on giving. The operator supports an TapObserver
interface that can be used instead of the callback function we used in our earlier examples:
As a result, we can register several side effects in our code based on any of these notifications as follows:
Most of these notifications are explicit in what they do, but let’s document all six of them for the sake of clarity:
next
: Invoked whenever the Observable receives new dataerror
: Invoked whenever an error occurs within the Observablecomplete
: Invoked when the Observable completes and stops emitting any new values.subscribe
: Invoked whenever a new subscriber subscribes to the Observableunsubscribe
: Invoked whenever a subscriber unsubscribes from the Observablefinalize
: Invoked whenever the Observable is done, either because of an error, of completion, or unsubscription. It’s like a catch-all notification to mark the end of an Observable.
You can see an example of such TapObserver
in action here on Stackblitz.