C# Event Programming – Are EventHandler and IObservable Interchangeable?

cevent-programmingobserver-pattern

I have an object which will periodically raise an event based on an action performed in an application. This will be heard by any listener(s) and acted upon accordingly.

I do not wish to use a custom type for this and would like to make use of either EventHandler<T> or IObservable<T> to manage the pub/sub mechanism I am looking to put in place.

I have had a play with both and they both do what I require.

I have read through the MSDN Observer Design Pattern and MSDN Events Programming Guide, however, I remain uncertain as to if one mechanism is more appropriate than the other.

Is one more suited for my scenario than the other or are both suitable and merely down to personal choice?

Edit 1

My pub/sub requirements are not at the UI layer at this point and are lower down. My publisher is monitoring network activity and raising an event based on certain network events. The subscriber is responsible for listening for raised events and performing an associated action. The UI is not involved at this point.

Best Answer

As I understand it, the Observable pattern concerns itself traditionally with real-time binding of a User Interface, based on changes in the underlying data store. In other words, a UI that subscribes to an IObservable<T> has updates pushed to it when the underlying data store changes.

Event Handlers are a more generalized mechanism. They are used for all sorts of things, both inside the UI and elsewhere. Fundamentally, EventHandler<T> is really just a formal definition for a delegate signature that's been around since the beginning of Windows Forms.