skip to content

tap vs finalize

 

Both operators can be used to trigger sideeffects on error/complete stream events. While tap can distinguish error from complete, finalize will also be triggered on unsubscription:

Open browser console to see the output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const { rxObserver } = require('api/v0.3');
const { timer } = require('rxjs');
const { finalize, tap } = require('rxjs/operators');

// you'll need to open console
// for this example

const sub = timer(10)
  .pipe(
    finalize(()=>
      console.log(`Finished @ ${ Date.now() }ms`)
    ),
    tap({
      next(n){ console.log(n) },
      error(e){ console.log(e) },
      complete(){ console.log('C') }
    })
  )
  .subscribe(rxObserver());


// uncomment next line to trigger only finalize
// setTimeout(() => sub.unsubscribe(), 5)

0msstartcomplete00