Thursday, April 1, 2010

Tracking events with Rx in Silverlight

When you want to execute some code after multiple events have been completed, you don’t always know which event will be triggered first, you might have to synchronize them using some boiler plate logic.  This could, for example,  happen when you have to execute two service calls at the same time.

The solution for this problem comes with the Rx framework, the System.Reactive assembly found in the Silverlight Toolkit.

Image you have two events coming from “serviceProxy”, you could make them observable like this.

IObservable<Event<EventArgs>> observable1
    = Observable.FromEvent<RoutedEventArgs>(serviceProxy, "EventOne");

IObservable<Event<EventArgs>> observable2
    = Observable.FromEvent<EventArgs>(serviceProxy, "EventTwo");

You can execute the following Rx method to make sure only a composite event is triggered once both events have been triggered. 

IObservable<Event<EventArgs>> joinedObservable = observable1.ForkJoin(observable2);

To be able to now execute our event we can simply call the Subscribe method and execute a action of our choice :

joinedObservable.Subscribe( /* Some Method */ );