Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

events

haskell

f#

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.

like image 265
Cetin Sert Avatar asked Jul 31 '12 19:07

Cetin Sert


1 Answers

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.

like image 116
Tomas Petricek Avatar answered Oct 22 '22 15:10

Tomas Petricek