tap / do
signature: tap(nextOrObserver: function, error: function, complete: function): Observable
tap(nextOrObserver: function, error: function, complete: function): Observable
Transparently perform actions or side-effects, such as logging.
๐ก If you are using as a pipeable operator, do
is known as tap
!
Examples
Example 1: Logging with tap
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { of } from 'rxjs';
import { tap, map } from 'rxjs/operators';
const source = of(1, 2, 3, 4, 5);
// transparently log values from source with 'tap'
const example = source.pipe(
tap(val => console.log(`BEFORE MAP: ${val}`)),
map(val => val + 10),
tap(val => console.log(`AFTER MAP: ${val}`))
);
//'tap' does not transform values
//output: 11...12...13...14...15
const subscribe = example.subscribe(val => console.log(val));
Example 2: Using tap with object
( StackBlitz)
// RxJS v6+
import { of } from 'rxjs';
import { tap, map } from 'rxjs/operators';
const source = of(1, 2, 3, 4, 5);
// tap also accepts an object map to log next, error, and complete
const example = source
.pipe(
map(val => val + 10),
tap({
next: val => {
// on next 11, etc.
console.log('on next', val);
},
error: error => {
console.log('on error', error.message);
},
complete: () => console.log('on complete')
})
)
// output: 11, 12, 13, 14, 15
.subscribe(val => console.log(val));
Related Recipes
Additional Resources
tap ๐ฐ - Official docs
tap - In Depth Dev Reference
Logging a stream with do ๐ฅ ๐ต - John Linquist
Utility operator: do ๐ฅ ๐ต - Andrรฉ Staltz
Build your own tap operator ๐ฅ - Kwinten Pisman
๐ Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/tap.ts
Last updated