有没有办法在不使用 Subject 的情况下创建由方法调用触发的可观察序列? [英] Is there a way to create an observable sequence triggered by method calls without using Subject?

查看:29
本文介绍了有没有办法在不使用 Subject 的情况下创建由方法调用触发的可观察序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务有几个方法,在我的代码中的不同地方调用.

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

class Service {
  method1() {
  }

  method2() {
  }

我希望能够订阅这些方法调用,即有一个 observable,每当调用这些方法之一时,它就会发出一个值.我意识到我可以用 Rx.Subject 做到这一点,但我想知道是否有办法做到这一点,因为我的案例不满足列出的要求 这里 即我不需要热观察.>

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.

推荐答案

使用主题.根据定义,您想要的 observable 是热的.

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

再次通读Hot and Cold Observables 文章.这是重要的一点:

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

Hot observables不会导致订阅副作用.

Hot observables do not cause subscription side effects.

冷的 observable 确实会导致订阅副作用;然而,我们必须假设任何温度未知的可观测对象都是冷的,有时这个假设是错误的;因此,更准确的定义是:

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:

冷 observables可能导致订阅副作用.

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.

这篇关于有没有办法在不使用 Subject 的情况下创建由方法调用触发的可观察序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆