如何实现从一个IObserver到另一个IObserver的原子切换?
我有一个 IObservable
,我使用一些中间步骤将其转换为 IObservable
:
var observedXDocuments =
from b in observedBytes
// Lot of intermediate steps to transform byte arrays into XDocuments
select xDoc;
在某个时间点,我对观察到 XDocument
,因此我订阅了 IObserver
。稍后,我想订阅另一个 IObserver
如何在一个原子操作中完成此操作,而不丢失任何观察到的 XDocument
?我可以这样做:
oldObserver.Dispose();
observedXDocuments.Subscribe(newObserver);
不过我担心,在这两个调用之间,我可能会丢失一个XDocument
。如果我切换这两个调用,可能会两次收到相同的 XDocument
。
I have an IObservable<byte[]>
that I transform into an IObservable<XDocument>
using some intermediate steps:
var observedXDocuments =
from b in observedBytes
// Lot of intermediate steps to transform byte arrays into XDocuments
select xDoc;
At some point in time, I'm interested in the observed XDocument
s so I subscribe an IObserver<XDocument>
. At a later point in time, I would like to subscribe another IObserver<XDocument>
and dispose of the old one.
How can I do this in one atomic operation, without loosing any observed XDocument
? I could do something like:
oldObserver.Dispose();
observedXDocuments.Subscribe(newObserver);
I'm worried though, that between these two calls, I could loose an XDocument
. If I switch the two calls, it could happen that I receive the same XDocument
twice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可能会添加一个间接层。编写一个名为 ExchangeableObserver 的类,将其订阅到您的可观察对象,并使其永久订阅。 ExchangeableObserver 的工作是将所有事情委托给给定的子观察者。但程序员可以随时更改委托的子观察者。在我的示例中,我有一个 Exchange() 方法。像这样的东西:
I'd probably add a layer of indirection. Write a class called ExchangeableObserver, subscribe it to your observable, and keep it permanently subscribed. The job of ExchangeableObserver is to delegate everything to a given sub-observer. But the programmer is allowed to change the sub-observer being delegated to at any time. In my example I have an Exchange() method. Something like:
您可以使用一个信号量,确保在
IObservable
准备IObservable
时不会发生观察者更改。伪代码如何做到这一点(不是测试)
编辑:使用
Call IObservable
我解释你的句子
,你已经为事件的东西。
IObservable注册了一个事件处理程序
从byte[]
创建一个XDocument
然后调用触发 IObservable
Call IObservable
表示触发后续事件的代码you can use a semaphore that makes shure that while
IObservable<byte[]>
prepares forIObservable<XDocument>
no observer-change takes place.pseudocode how this could be done (not testet)
Edit: with
Call IObservable<XDocument>
I interprete your sentense
that you have registered an eventhandler for
IObservable<byte[]>
that creates aXDocument
frombyte[]
and then callssomething that triggers an event for
IObservable<XDocument>
.Call IObservable<XDocument>
means the code that triggers the followup-event