Rx Observable Event Dissection
Monday, January 12, 2015 Category : CEP, Reactive Extensions, RX 0
So, in the last post, we discussed a simple example of how RX can be used for subscribing to an event and receive updated whenever that event is fired. This post discusses the code for defining an "observable" a bit in detail.
So, the code that was used for defining the observable event was:
IObservable<EventPattern<object>> eventAsObservable = Observable.FromEventPattern(
ev => dg.ev += ev,
ev => dg.ev -= ev);
The FromEventPattern method should be used when subscribing to an event that conforms to a standard .NET event pattern, i.e. of the form:
public delegate void EventHandler(object sender, EventArgs e);
But what if we don't have a standard .NET event? What if we have defined our own event with custom event arguments? For example, say the event is:
event MarketDataReceivedHandler DataReceived;Where MarketDataReceivedHandler is defined as:
public delegate void MarketDataReceivedHandler(MarketDataEventArgs updates);With MarketDataEventArgs class defined as:
public class MarketDataEventArgs : EventArgs { public MarketData Payload { get; set; } }
In this case, RX provides another method for subscription - Observable.FromEvent
This method does the same thing as the FromEventPattern method. For FromEventPattern, we only defined a lambda for subscribing to the target event. For FromEvent also, we can do the same:
eventAsObservable = Observable.FromEvent<MarketDataReceivedHandler, MarketDataEventArgs>( mktH => _provider.DataReceived += mktH, mktH => _provider.DataReceived -= mktH );The above code translates to the following statement: "Define an observable of type MarketDataReceivedHandler, which when raised, provides contains arguments of type MarketDataEventArgs and also, remove the makeshift handler when the subscription is disposed."