Friday, 17 February 2012

Rx Event Example

When subscribing to events Reactive Extensions (Rx) is a powerful way to filter, throttle and compose your .Net code. 

With this example I have a WPF application that listens to a FxRate pricing service, that’s pumping out 100 new prices a second via an event.

I’m going to make available the code to show how to hook up the front end Metro style application using MVVM with:

  • old skool event handlers
  • and then using Reactive Extensions (Rx)

Finally we update the Rx example to filter on just one of the exchange rates and also throttle back the rate of FxRates being received to one per second.


The event signature

Old skool event handlers

Using MVVM, here we have my view model code stripped back just to show we have:

  • A pricing service
  • A subscribed command (data bound to the subscribed button on the UI) which toggles the subscribed property
  • A delegate (PriceUpdate) that handles the event when the subscribed button is clicked.  Click the button a second time to unsubscribe and remove the delegate from handling the event

Lines 25 and 30 show the adding and removal of the event handler, dependent on whether the user has clicked the subscribe button.

Rx Subscriptions

To do the same thing with Rx takes two lines of code (lines 18/19 and 21)

Filtering with Rx

Simply update our subscription to include a where filter that accepts the event coming in (e) and sets the predicate to Ccy (Currency) for the exchange to Euro to GBP.

Throttling with Rx

NOTE:  The code below was a workaround, please use Sample as shown here.

So we have filtered the events to only give us the Euro to GBP prices. Now let's enhance the solution just to give us the latest Euro to GBP price every two seconds.

Source code

Event handlers:

Reactive Extensions:


  1. It’s very rare that you find the relevant information on the net but your article did provide me the relevant information. I am going to save your URL and will definitely visit the site again.
    web hosting company

  2. Click the button a second time to unsubscribe and remove the delegate from handling the event.