in which case is better to put callback for the error inside tap instead of subscribe?

Viewed 57

I know that tap is use for side effects of an Observable, i see that it's similar to subscribe. here is an example:

import { from } from 'rxjs';
import { tap } from 'rxjs/operators';

observable$ = from([1,2,3,4]);

// we can add error callback in tap

observable$.pip(
 tap({
    next(value) { console.log(value) },
    error(error) { console.log(error) }
 })
).subscribe(console.log);


// and we can do it inside subscribe

observable$.pip(
 tap()
).subscribe(
    (value) => {console.log(value)},
    (error) => { console.log(error)
);

what is the difference in details and in which cases, tap will be useful

2 Answers

Tap's signiture is

 tap(nextOrObserver: function, error: function, complete: function): Observable

and is used when you use pipe in your subscription and basically means do something

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}`))
);

You have it right in that example: the functions passed to tap and to subscribe are doing the same thing. At that point it is a matter of preference.

For me, I only use tap when it is a true side effect. Meaning, if the reason I am subscribing to the stream is to do thisFunction() then I put thisFunction() inside of the subscribe block.

For example, if it is a choice between:

stream$.pipe(
     tap(doSomething)
).subscribe();

and

stream$.subscribe(doSomething);

I'll always choose that last one.

Related