When should we use the RxJS tap operator?

馋奶兔 提交于 2020-03-01 03:38:29

问题


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


回答1:


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.




回答2:


You can use it to perform a side effect for example. Or you can use it to see what's the current value that is being passed around without affecting/modifying the Observable. So something like a console.log() but inside the stream.




回答3:


Decalration

public tap(nextOrObserver: Observer | function, error: function, complete: function): Observable 

tap is replacement of do operator which returns observable identical to your source observable. for each value emitted, perform a side-effect. it has 3 optional parameters.

  • nextOrObserver: A normal Observable object to perform side effect.
  • error: Callback for errors in source Observable.
  • complete: Callback for completion of the source.

Recommended for debugging purpose.



来源:https://stackoverflow.com/questions/54289549/when-should-we-use-the-rxjs-tap-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!