如何创建一个 Rx observable,当最后一个观察者取消订阅时停止发布事件?
我将创建一个可观察量(通过各种方式)并将其返回给感兴趣的各方,但是当他们听完后,我想拆除可观察量,这样它就不会继续消耗资源。另一种方式是将其视为在 pub 子系统中创建主题。当没有人再订阅某个主题时,您不想再保留该主题及其过滤。
I'll create an observable (through a variety of means) and return it to interested parties, but when they're done listening, I'd like to tear down the observable so it doesn't continue consuming resources. Another way to think of it as creating topics in a pub sub system. When no one is subscribed to a topic any more, you don't want to hold the topic and its filtering around anymore.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rx 已经有一个运算符可以满足您的需求 - 实际上是两个 -
Publish
&参考计数
。以下是如何使用它们:
简单。
Rx already has an operator to suit your needs - well two actually -
Publish
&RefCount
.Here's how to use them:
Simple.
如果我理解你的问题,你想要创建可观察量,以便当所有订阅者都处理了他们的订阅时,即没有更多订阅者,那么你想要执行一个清理函数,这将阻止可观察量产生进一步的值。
如果这是您想要的,那么您可以执行如下操作:
//使用示例:
If I have understood your question you want to create the observable such that when all subscribers have disposed their subscription i.e there is no more subscriber, then you want to execute a clean up function which will stop the observable from production further values.
If this is what you want then you can do something like below:
//Usage example: