What are the similarities / differences between Control.Observable and Control.Event modules in F#?

前端 未结 1 1268
独厮守ぢ
独厮守ぢ 2021-02-20 03:42

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
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-20 04:21

    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:

    • IEvent does not support removing of event handlers, so when you create a processing pipeline (combining map, filter and others) and then call RemoveHandler on 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 hand IObservable is able to remove handlers.

    • As a result of the previous point, IObservable behaves differently with respect to stateful combinators. For example, when you use Event.scan, you can attach multiple handlers to the resulting event and they will see the same state. IObservable creates a "new state" for every attached handler (unless you use subject explicitly).

    In practical F# programming, this means:

    • You should generally prefer IObservable if you want to be able to remove event handlers (using RemoveHandler or when using AwaitObservable in F# async workflows).

    • If you want to declare events (usable from C#) then you need to create properties of type IEvent and so you need to use Event combinators.

    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.

    0 讨论(0)
提交回复
热议问题