在 RX 中同步多个订阅
是否可以强制对不同的可观察量进行多个 RX 订阅串行运行(而不是同时运行)?
我知道我可以使用 EventLoopScheduler 来实现这一点,但这会降低性能,因为所有处理都将在单个线程上完成。
Is it possible to force multiple RX subscriptions to different observables run serially (not simultaneously)?
I am aware that I can use EventLoopScheduler for that, but that will degrade performance because all handling will be done on a single thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您打算运行一个可观察对象直到
OnCompleted
,然后开始下一个,您应该查看Concat
。如果您打算同时订阅多个不同的可观察量,则可以使用合并(如果语义对您的场景有意义)。如果 Merge 不合适,我建议在观察者方法或您已经了解的 EventLoopScheduler 中使用标准线程同步方法之一(锁定、监视器等)。编辑保留在下面的原始答案
是的,可以强制串行观察者执行。然而,是否需要取决于可观察到的情况。一般来说,热可观察量已经串行运行,而冷可观察量则不会。这是热可观测值和冷可观测值工作方式差异的副作用。要将冷的可观察对象变为热对象,从而使观察者串行运行,请使用
Publish
。这是演示各种行为的示例。If you mean to run one observable until
OnCompleted
then start the next, you should look intoConcat
. If you mean to have multiple different observables that are subscribed to at the same time, you could useMerge
(if the semantics make sense for your scenario). If Merge is not appropriate, I would recommend using one of the standard thread synchronization methods (lock, Monitor, etc) in the observer methods or the EventLoopScheduler you already know about.EDIT Original answer preserved below
Yes, it is possible to force serial observer execution. However, whether you need to or not depends on the observable. In general, hot observables will already run serially, whereas cold observables will not. This is a side-effect of the difference in the way hot and cold observables work. To make a cold observable hot, and thus make observers run serially, use
Publish
. Here's an example demonstrating the various behaviors.