BACK
Lessons16. tap: look without changing
Lessons · 16

16. tap: look without changing

tap — look without touching

The tap(fn) operator calls a function for each value but doesn't change the stream. Whatever goes into tap comes out unchanged.

of(1, 2).pipe(
  tap(value => console.log('saw', value)),
  map(value => value * 10)
)
// tap prints 1, then passes 1 on to map → 10
// tap prints 2, then passes 2 on to map → 20

When to use tap

  • Debugging: see what arrives at a specific point in the pipe.
  • Analytics, logging, writing to localStorage — anywhere there's a side effect but no need to change the value.

Don't confuse it with map

If the function should transform the value, use map. If you only want to look or do something "on the side," use tap. In tap, the return value is ignored.

Glossary

  • Side effect — any action other than returning a new value: a log, a DB write, a DOM change, firing analytics.

Your task

  1. In pipe, add three operators in order (comma-separated):
  2. tap(value => console.log('Before: ' + value)) — look at the value before map.
  3. map(value => value * 5) — multiply by 5.
  4. tap(value => console.log('After: ' + value)) — look at the value after map.
  5. Expected output: Before: 1 → After: 5 → Final: 5 → Before: 2 → After: 10 → Final: 10. Notice: each value runs through the whole pipe completely before the next one starts.
Solution spoiler · click to reveal
const { of, tap, map } = Rx;

const result$ = of(1, 2).pipe(
  tap(value => console.log('Before: ' + value)),
  map(value => value * 5),
  tap(value => console.log('After: ' + value))
);

result$.subscribe(value => {
  console.log('Final: ' + value);
});
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...