Overview
Thetap operator is used to perform side-effects for notifications from the source Observable without modifying the emitted values. It’s designed as a designated place for side-effects, helping keep other operators pure.
tap returns an exact mirror of the source Observable. Any error that occurs synchronously in a handler will be emitted as an error from the returned Observable.Signature
Parameters
A next handler function or a partial observer object. Can include:
next: Callback for each emitted valueerror: Callback for error notificationscomplete: Callback for completion notificationsubscribe: Callback invoked when source is subscribed tounsubscribe: Callback invoked on explicit unsubscribe (not on error/complete)finalize: Callback invoked on any finalization (error, complete, or unsubscribe)
Returns
A function that returns an Observable identical to the source, but runs the specified observer or callback(s) for each item.
TapObserver Interface
Usage Examples
Basic Debugging
The most common use case - logging values as they pass through:Lifecycle Callbacks
Usingtap to track subscription lifecycle:
Validation and Error Handling
Force errors based on emitted values:Sequence Tracking
Track completion of sequential operations:Common Use Cases
- Logging and Debugging: Insert
tapanywhere in the observable chain to log values - Updating State: Trigger state updates as a side-effect of emissions
- Analytics: Track user interactions without affecting the data flow
- Caching: Store values in a cache as they pass through
- Progress Tracking: Update UI progress indicators
Best Practices
- Keep
taphandlers pure when possible - avoid mutations - Use
tapfor side-effects only, not for transforming values (usemapinstead) - For finalization logic, consider using
finalizeoperator if you don’t need other tap features - Remember that synchronous errors in tap handlers will error the entire stream
Related Operators
- finalize - Execute callback on finalization only
- map - Transform values (not side-effects)
- switchMap - Map to inner observables
