Saturday, November 7, 2009

Silverlight Rx : System.Reactive

Yesterday I came across the System.Reactive assembly that is included with the Silverlight Toolkit.  On the blog of Jafar Husain

He has made a lot of posts about the Rx framework, and it is definitely interesting to read!

http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html

We can program in reaction to events and apply our logic on them. We could for example do some action only when an event is raised with a certain event argument. This embeds the Async handling of events and allows this code to be unit tested.

The big problem with asynchronous programming is that the code very quickly gets unreadable and hard to maintain, as it is not always clear how several events are linked to one another.

The Reactive framework works with the IObserver and the IObservable classes, which can be thought of as Reactive versions of IEnumerable in the context of Linq ( actually the extension methods have been added to the System.Linq namespace ).  You basically look at the events being thrown as a collection you can browse trough.

So how does it work.

To quickly show how we can use Rx to simplify our code, We will write an extension method that will call a web client's DownloadString method and return a String.

public static class WebClientExtender
{

public static IObservable<string> GetSite(this WebClient client, string url)
{
var downloaded = Observable.FromEvent<DownloadStringCompletedEventArgs>
                 (client, "DownloadStringCompleted");
client.DownloadStringAsync(new Uri(url));
return downloaded.Select(x=>((DownloadStringCompletedEventArgs)x.EventArgs).Result);
}

}

To call this we can now simple add the following line of code to our Silverlight application.

new WebClient().GetSite("http://localhost/").Subscribe(x => MessageBox.Show(x));

This way we can very easily clean up the code and structure how the Asynchronous events are handled.

No comments:

Post a Comment