Over at Channel9 they’ve recently uploaded a couple of videos on a new feature of .NET 4.0 called the Reactive Framework:

Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx)

Kim Hamilton and Wes Dyer: Inside .NET Rx and IObservable/IObserver in the BCL (VS 2010)

What is the Reactive Framework? I’ll try to explain it briefly, but if you want to skip to the end of this post, I’ll add some links to other blogs that you should check out.

The .NET framework right now provides a pair of classes that can be used to iterate over a collection of objects: IEnumerable<T> and IEnumerator<T>. Enumerable objects provide the actual list, while enumerators do the “heavy lifting” of asking for the current item and moving forward through the list. When you think about it, this is a “pull” operation – the enumerator is “pulling” the data from the enumerable.

The Reactive Framework (Rx) introduces a new pair of classes: IObservable<T> and IObserver<T>. Observable objects provide a way to “subscribe” to events, and observers (which do the subscribing) are notified when those events happen. In a way it’s a bit like traditional events in the framework, but with a game-changing addition: It’s queryable from LINQ.

What does this mean? It means you can do ridiculous LINQ queries like this one, which sets up an observer that only reacts when the user presses the a, b and c keys successively:

IObservable<Unit> abcPressed =
   from firstKeyPressEvent in pressedIs(Key.A)
   from secondKeyPressEvent in pressedIs(Key.B).Take(1).Until(pressedIsNot(Key.B))
   from thirdKeyPressEvent in pressedIs(Key.C).Take(1).Until(pressedIsNot(Key.C))
   select new Unit();

abcPressed.Subscribe(() => Debug.WriteLine("ABC was pressed."));

Weird? Yeah, today it’s weird. I have a feeling that, a year or two from now, this sort of “querying events” code will be a very natural way to code.

For more information on the Reactive Framework, a good place to start is Jafar Husain’s blog “unfold”, specifically this post:

Introducing Rx (Linq to Events)

You should also check out Paul Baturn’s series of posts entitled “Reacting to the Reactive Framework”. Start with part one here:

Reacting to the Reactive Framework: Part 1