问题
F# (at least in Visual Studio 2012) has both Control.Observable and Control.Event.
- How are they related?
- Which one should be used when?
- Are there performance differences between the two?
I would also love to know what Haskell modules / packages / features the .NET IEnumerable / IObservable duality achieved with reactive extensions to .NET correspond to.
回答1:
To answer the first part of your question, there is a number of differences between IEvent and IObservable. The reason why there are two similar types is that IEvent has been designed for F# (earlier and it is left there mostly for compatibility reasons) and the IObservable type was added later on to the .NET (and so F# added support for it too). Here are some differences:
IEventdoes not support removing of event handlers, so when you create a processing pipeline (combiningmap,filterand others) and then callRemoveHandleron the resulting event, it leaves some handlers attached (yes, that's a leak and we wrote a more detailed paper about it) On the other handIObservableis able to remove handlers.As a result of the previous point,
IObservablebehaves differently with respect to stateful combinators. For example, when you useEvent.scan, you can attach multiple handlers to the resulting event and they will see the same state.IObservablecreates a "new state" for every attached handler (unless you use subject explicitly).
In practical F# programming, this means:
You should generally prefer
IObservableif you want to be able to remove event handlers (usingRemoveHandleror when usingAwaitObservablein F# async workflows).If you want to declare events (usable from C#) then you need to create properties of type
IEventand so you need to useEventcombinators.
As mentioned in comments, the F# model is heavily influenced by functional reactive programming (FRP) which is an idea that was first developed in Haskell, so you should find a plenty of similar libraries. The F# version is "less pure" in order to be more practical for .NET programming.
来源:https://stackoverflow.com/questions/11747861/what-are-the-similarities-differences-between-control-observable-and-control-e