Event and Observable in FSharp

廉价感情. 提交于 2019-12-03 16:26:58

问题


Is it equivalent/better to work

  • with the Event module on Event type
  • or with Observable on the publish property of an event

Functionally it seems equivalent, and I guess the difference is 'semantic' :

  • Are we inside the boundary where it makes sense to have access to the internal state of the event ?
  • Or are we considering this event interface as a passive source from which a stream was exposed to us

Is that the correct thinking ?


回答1:


The main difference between Event and Observable is in how they handle state and un-subscription.

  • Event functions attach to the source event and do not give you any way to unsubscribe. If you use stateful combinators (like Event.scan) and then attach multiple observers to the resulting event, then they will all see the same state.

  • Observable functions construct "specification" of the processing pipeline. When you attach a handler to IObservable value, you get back an IDisposable that can be used to remove all handlers. Each handler attached to IObservable will get a new state (because the runtime creates a new processing chain according to the "specification").

In practice, the main difference is in the statfullness - if you want to share state, you can use the Event module - implementing the same using Observable is possible but harder.

If you're using events inside async, then you should use Observable and AwaitObservable (instead of built-in AwaitEvent), because using event combinators will leak memory - it will attach event handlers that are never removed.



来源:https://stackoverflow.com/questions/15549384/event-and-observable-in-fsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!