Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event and Observable in FSharp

Tags:

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 ?

like image 312
nicolas Avatar asked Mar 21 '13 13:03

nicolas


1 Answers

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.

like image 83
Tomas Petricek Avatar answered Sep 29 '22 16:09

Tomas Petricek