LINQ into the data stream

There have been a couple of recent channel9 interviews covering Rx: The Livelabs Reactive Framework. You can find them here and here. Currently the only release of this framework is as part of the Silverlight Toolkit. However, using the awesome Cecil, you can modify the assembly to run on top of the standard 3.5 framework.
 
It is then really easy to get some simple examples going. Start a WindowsForms project, set a reference to the System.Reactive.dll, add a button and a couple of text boxes and try the following.
 

  IObservable<Event<EventArgs>> button = Observable.FromEvent<EventArgs>(button1, "Click");
  button.Subscribe(() =>
MessageBox.Show("Hello"));

That example causes a message box to appear everytime the button is clicked.
 
The real power of the Reactive framework is that LINQ queries can be used against it, so we could decide to update a second textbox only when the number of characters in the text is even.

  IObservable<Event<EventArgs>> text = Observable.FromEvent<EventArgs>(textBox1, "TextChanged");
  var data = from _ in text select textBox1.Text;
 
var eventLengthData = from x in data where x.Length % 2 == 0 select x;
  eventLengthData.Subscribe(datum => textBox2.Text = datum);

We can have multiple subscribers to the event stream, so we can print out all of the content changes even if we only update the textbox when the data length is even.

  data.Subscribe(x =>

Console.WriteLine(x));

This concept of merging the streams of data can lead to some interesting results. We’ll look at the example of the generation of a suggestions list for a given set of textbox data, but that will have to wait until next time.

Of course, there are always complications to do with side-effects and threads and their associated synchronisation contexts. There’s a good post here discussing some of this in relation to LINQ.

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s