如何避免在RX中使用主题 [英] How to avoid the use of Subjects in RX
问题描述
所以我一直读到所有使用Subject<T>
都是不好的"的说法-我有点同意这个推理.
So I keep reading everywhere that use of Subject<T>
is "bad" - and I kind of agree with the reasoning.
但是,我正在尝试避免使用它的最佳方法,并举一个例子.
However, I am trying to think of the best way to avoid using it and have an example.
当前,我为持久性配置类提供了一个抽象类,该类上具有受保护的Save()
方法,只要更改属性就可以持久化该类,就会调用该方法.该消息将消息泵送到Subject<T>
上,该消息通过IObservable<T>
接口公开,串行化服务侦听并串行化该类.这似乎是当时实现这一目标的最明显,最简单和最快的方法.
Currently I have an abstract class for my persisted configuration classes that has a protected Save()
method on it which is called whenever changing a property should persist the class. This message pumps a message onto a Subject<T>
which is exposed through IObservable<T>
interface which the serialisation services listens to and serialises the class. This seemed the most obvious, simple and quickest way to implement this at the time.
那么不使用Subject的RX方法是什么?我会公开一个事件并使用Observable.FromEventPattern()
订阅该事件吗? -因为这似乎是更复杂的解决方法.
So what would be the RX way to do this without using a Subject? Would I instead expose an event and use Observable.FromEventPattern()
to subscribe to it? - as this seems a more complex way to go about it.
推荐答案
Subject<T>
的使用并没有什么坏处-必须有某种输入monad"的方式-这是学术上的说法获取IObservable<T>
" .您需要从某个地方开始.
It's not so much that the use of Subject<T>
is bad - there has to be some way of "entering the monad" - that's the academic way of saying "get an IObservable<T>
". You need to start somewhere.
在订阅中使用Subject<T>
而不是将现有的可观察对象链接在一起时,会出现更多的问题.主题应该只存在于Rx机器的边缘.
The problem with Subject<T>
arises more when it's used from a subscription instead of chaining existing observables together. Subjects should just exist at the edges of your Rx machinery.
如果提供的所有入口点(例如FromEvent
,FromEventPattern
,FromAsync
,Return
,ToObservable()
等)均不适合您,则使用Subject<T>
是完全有效的.而且,无需为了促进使用上述方法之一而增加额外的复杂性-无论如何,其中大多数都使用主题或类似主题的构造.
If none of the provided entry points (e.g. FromEvent
, FromEventPattern
, FromAsync
, Return
, ToObservable()
and so on) work for you then using Subject<T>
is perfectly valid. And there's no need to add extra complexity just to facilitate using one of the above - most of them use subjects or subject-like constructs under the covers anyway.
在您的情况下,听起来像Subject<T>
很好.您可能会想通过 AsObservable()
公开它为了隐藏实施细节.
In your case, sounds like Subject<T>
is just fine. You might what to look at exposing it via AsObservable()
in order to hide the implementation details.
这篇关于如何避免在RX中使用主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!