Is there a way to create an observable sequence triggered by method calls without using Subject?

时光毁灭记忆、已成空白 提交于 2020-01-02 07:49:35

问题


I have a service with a couple of methods, called in various different places in my code.

class Service {
  method1() {
  }

  method2() {
  }

I'd like to be able to subscribe to those method calls, ie have an observable which emits a value whenever one of those methods is called. I realize I can do this with an Rx.Subject but I'm wondering if there's a way to do it without, because my case doesn't satisfy the requirements listed here ie I don't need a hot observable.


回答1:


Use a subject. Your desired observable is, by definition, hot.

Read through the Hot and Cold Observables article again. Here's the important bit:

Hot observables do not cause subscription side effects.

Cold observables do cause subscription side effects; however, we must assume that any observable with an unknown temperature is cold, and sometimes that assumption will be wrong; therefore, a more accurate definition is:

Cold observables may cause subscription side effects.

In your case, code is calling your methods whether or not anything "subscribes" to be notified when the methods are called. Subscribing for notifications does not trigger any activity or changes in behavior. In fact, late subscribers will "miss" calls made before they subscribed.



来源:https://stackoverflow.com/questions/38148646/is-there-a-way-to-create-an-observable-sequence-triggered-by-method-calls-withou

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