tap() vs subscribe() to set a class property

前端 未结 3 479
南方客
南方客 2020-12-24 06:01

I am very new to rxjs and was just wondering is it ok to setup a class property by piping the stream and tapping it, or it should i do it in the subscribe. To me either way

3条回答
  •  萌比男神i
    2020-12-24 06:43

    Good question. In the source code for the tap operator, this comment pretty much sums it up:

    This operator is useful for debugging your Observables for the correct values or performing other side effects.
    Note: this is different to a subscribe on the Observable. If the Observable returned by do is not subscribed, the side effects specified by the Observer will never happen. do therefore simply spies on existing execution, it does not trigger an execution to happen like subscribe does.

    Any side effect you can run in a tap can probably also be put in the subscribe block. The subscribe indicates your intent to actively use the source value since it's saying "when this observable emits, I want to save it's value in the applicants variable". The tap operator is mostly there for debugging, but it can be used to run side effects.

    In general, favor the subscribe block for running side effects, use tap for debugging, but be aware that tap can do more if you need it to.

提交回复
热议问题