Search code examples
rxjsrxjs6

When should we use the RxJS tap operator?


I do not understand from the docs. Could anyone explain it to me?


Solution

  • Most of the operators are working in streamed sequence, for example:

    source$.pipe(
      map((a: string) => changeAndReturnArray(a)),
      filter((b: string[]) => giveMeOnlySymbolsThatAreAfterNInAlphabet(b)),
      switchMap((c: string[]) => putToSomeObservable(c))
      ....
    );
    

    In that example you are not 'breaking' the stream, or jumping outside of it to do some external action. Jumping outside of stream is possible with tap operator, where you can:

    • call functions that will cause some side effect, that might be visible to end user (for example - display dialog, show snackbar, redirect to different route (but in my opinion it's not recommended to use tap in that way))
    • dispatch actions for store (if you are using any - for example ngrx store)
    • debug you're code -> console.log()
    • anything what can be considered as 'side effect' for your stream.

    My personal opinion - use 'tap' only if you can't find any better solution. Jumping outside of stream and calling some side effect can be double edged sword, especially when your dealing with some bigger application. Side effect are always harder to maintain, and you can finish with application that is doing magic stuff without any reason.