A common UI problem

This blog post is all about a common UI-related programming problem. Ever since my first UI-based application I’ve come across with this problem and never found a satisfying way to resolve it (until now 😉 ). This first blog post is about describing the problem and my former solution approaches. In the next blog post I will demonstrate a more proper solution.

The code in these two blog posts is using WinForms and C#, but it should be easy adoptable to other UI technologies as well.

Problem description

It’s a common problem: you want to react on an event like the TextChanged event on a TextBox, but ONLY if the user changed the text and it’s not changed programmatically. For example you want to update some data, when the user changes the content of a TextBox, but this update process should not be triggered when the progam itself sets some data and therefore updates the text. The starting point for that could be something like the following code:

public partial class SomeControl : UserControl
{
    // ...

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _someTextBox.Text = value.SomeValue;
                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        // perform data/view update operations
    }
}

Here the OnSomeTextBoxTextChanged() method is bound to the _someTextBox.TextChanged event. ViewData is a class with arbitrary data that should show up in the UI.
Notice the problem: when the ViewData property is set programmatically the OnSomeTextBoxTextChanged() method is being executed, which is not what was intended (firing the event only when the user changes the value of the TextBox).

A similar problem arises with infinite loops. Imagine a user changes something in the UI and an event X is fired. You hook this event and start a complex UI workflow, which at the end fires the event X again. The proces is executed again and very easy you come into an infinite loop situation. If you are an UI developer you would very probably agree that UI event chains are often opaque and can get messy.

Let’s look at some obvious, however not very elegant, solutions.

Approach #1: Temporary event detach

One of those simple solution is the temporary detachment of the problematic event. For example if you don’t want to react on the TextChanged event when the TextBox.Text property is set programmatically, you could detach your event handler from TextChanged before setting the Text and afterwards attach it again. This approach is shown in the following example code:

public partial class SomeControl : UserControl
{
    // ...

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _someTextBox.TextChanged -= OnSomeTextBoxTextChanged;
                _someTextBox.Text = value.SomeValue;
                _someTextBox.TextChanged += OnSomeTextBoxTextChanged;

                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        // perform data/view update operations
    }
}

While this is working, it’s not a recommendable solution, because there are several shortcomings. First the manual event handling is not very intuitive and doesn’t explicitly reveal the intent of the programmer with this manual process. Thus your code is more difficult to read for others (and after some months for you as well). Moreover, you get undefined states when exceptions are thrown and caught in an outer component (and you miss a finally which attaches the event again). Then the event handler could be detached further on and the UI isn’t working properly afterwards. The whole event detach/attach process is getting very messy if you have complex views with many such problematic events. Last but not least this manual event handling process binds your code tightly to the view and you get trouble if you want to refactor several parts out.

Approach #2: Boolean flags

A similarly simple approach comes with boolean flags which indicate that a value is currently set programmatically and thus that Changed events should not be handled. The following code shows an example how this could solve our initial problem:

public partial class SomeControl : UserControl
{
    // ...

    private bool _isTextSetByProgram = false;

    private ViewData _viewData;
    public ViewData ViewData
    {
        get { return _viewData; }
        set
        {
            _viewData = value;
            if (value != null)
            {
                _isTextSetByProgram = true;
                _someTextBox.Text = value.SomeValue;
                _isTextSetByProgram = false;

                // other operations
            }
        }
    }

    private void OnSomeTextBoxTextChanged(object sender, EventArgs e)
    {
        if (!_isTextSetByProgram)
        {
            // perform data/view update operations
        }
    }
}

I think this is the most common solution that I’ve seen for the problem. For myself I must admit that I’ve mostly used this approach. But it has the same disadvantages like the event detach/attach solution (except the tight view coupling). Boolean variables don’t explicitly show the intent behind them and get likewise messy if used in complex situations where you could have dozens of those variables scattered around a view.

So while those solutions are very widespread and work they just don’t feel right and clean. But what’s the alternative? An interesting little one I will show you in the next post which comes shortly.

kick it on DotNetKicks.com

Some thoughts on Event-Based Components

The German software engineer Ralf Westphal currently spreads some knowledge about an alternative model for programming components and especially communication between them. Due to their nature they are called Event-Based Components. After some discussion with colleagues at SDX I want to share some of my thoughts on that with you (of course for further discussion as well).
The aim of Event-Based Components (EBC) is to create software components that are really composable without specific topological dependencies. You can compare EBCs with elements in electronic circuits. But first things first…

Interface-Based Components style

Normally we’re developing components in .NET as IBCs: Interface-Based Components. That means client classes have topological and functional dependencies to interfaces (or directly to other classes), which provide some sort of functionality. Well developed, such a dependency could be resolved with a Dependency Injection container like StructureMap:

class Program
{
    static void Main(string[] args)
    {
        // Bind (here: StructureMap)
        ObjectFactory.Initialize(x =>
        {
            x.For<IBusinessClient>().Use<BusinessClient>();
            x.For<IDataAccessComponent>().Use<DataAccessComponent>();
        });

        // Resolve and Run
        IBusinessClient client = ObjectFactory.GetInstance<IBusinessClient>();
        client.BusinessOperation(0);
    }
}

interface IBusinessClient
{
    void BusinessOperation(int personId);
}

class BusinessClient : IBusinessClient
{
    private readonly IDataAccessComponent _dataAccessComponent;

    public BusinessClient(IDataAccessComponent dataAccessComponent)
    {
        _dataAccessComponent = dataAccessComponent;
    }

    public void BusinessOperation(int personId)
    {
        Person p = _dataAccessComponent.GetPerson(personId);
        // do something ...
    }
}

interface IDataAccessComponent
{
    Person GetPerson(int id);
}

class DataAccessComponent : IDataAccessComponent
{
    public Person GetPerson(int id)
    {
        return  // ...some person...
    }
}

That’s pretty standard so far, isn’t it? In Ralf’s opinion this programming style lacks real composability of the components. Due to the topological dependency the clients is bound to a specific interface and no arbitrary component can perform the functionality. Instead a component has to implement the specific interface. You’re not able to use components which could provide the functionality, but don’t implement the interface…

Event-Based Components style

Ralf suggests Event-Based Components to the rescue. Components in this programming style can be compared to components in electronic circuits. Methods act as input pins of a component and can be called by other components. Events/delegates act as output pins and establish a connection to other components that should be used by the component or to provide calculation results. The output pins can be bound to any arbitrary method that meet the signature. Thus the dependency is still functional, but not topological any more.
The example above in EBC style could look as follows:

class Program
{
    static void Main(string[] args)
    {
        // Build
        var client = new BusinessClient();
        var dataAccess = new DataAccessComponent();

        // Bind
        client.GetPerson = dataAccess.GetPerson;

        // Run
        client.BusinessOperation(0);
    }
}

class BusinessClient
{
    public Func<int, Person> GetPerson { get; set; }

    public void BusinessOperation(int personId)
    {
        Person p = GetPerson(personId);
        // do something ...
    }
}

class DataAccessComponent
{
    public Person GetPerson(int id)
    {
        return  // ... some person ...
    }
}

This example shows the components BusinessClient and DataAccessComponent interacting as EBCs in a very simple form by using the Func<T> delegate type and thus enabling symmetric communication. Ralf encourages the use of standard input/output pins as Action<object>, which leads to asymmetric communication, because the DataAccessComponent would need to declare an output pin for providing the Person as result of GetPerson(). For the sake of simplicity I haven’t followed this principle here.

So the example uses a Func<T> delegate and no event. But you can still think of it as Event-Based Component, just because events are nothing more than multicast delegates. I could have used events instead of the simple delegate as well, but I’m quite fine, because I don’t need the functionality of multiple subscribers here.

As you can see from the example, just like IBCs the EBCs have some kind of initial Bootstrapper phase. This is the time when the components are composed. The output pins of a component’s client (BusinessClient in this example) are connected with the input pins of the component itself (here: DataAccessComponent).

Benefits

When I first saw EBCs I thought: „Dude, this is damn cool, isn’t it?“. Indeed this kind of programming style first feels strange and alternate and thus for me it’s really interesting. But are there some real benefits as well?

I think one big benefit of EBCs is their composability. A client hasn’t to know the interface of a component from which he wants to use some functionality. A component on the other side is not forced to implement an interface to provide some functionality, but it’s still retaining loose coupling. Even without interfaces the components are still independent from each other and have great testability.

Other benefits I see are the exchangeability and the topological independence. Components are not bound to a specific topological context in form of interfaces and thus are independent from topological changes on the interfaces. You can exchange the components easily by replacing the binding section with any other setup phase and can binding other methods to them. Especially your components are not forced to use (or implement) some kind of interface from which they will perhaps use just one single functionality…

Last but not least I see a very easy way to intercept calls and adding functionality without changing the components themselves. If you use events as output pins you can add some more event handlers in the binding phase. Thus you can easily integrate Logging, Tracing etc. into your applications. Of course you can achieve this with IBCs as well, I just say that EBCs are suiting very well for those requirements.

Drawbacks

Besides those benefits in my opinion there are some significant drawbacks as well.

First of all is the additional complexity which comes with EBCs. Composing EBCs can become complex, at least in projects of significant size. Due to binding methods and events together on the fine instead of interfaces on the coarse, there have to be much more binding statements. In fact you can think of an event’s signature as a one-method interface that has to be fulfilled from components. Furthermore (again especially in projects of a reasonable size) you will loose intelligibility and  overview over your system and the component interaction. Any arbitrary component can provide a functionality and there is no way to navigate between layers and components as clients and suppliers of functionality. Explicit interfaces are much more comprehensive than such „implicit“ specifications.  Perhaps in the future there will be tools that simplify composition between EBCs and navigation through EBCs, but until there’s such a tool I consider this as serious drawback.

Another drawback of EBCs is the loss of interfaces as formal contract of coherent functionality. Of course you can define interfaces and let your components implement them, but while clients are not compelled to use them they loose much of their value. Interfaces force components to implement a certain set of functionality completely and make this set explicit. Clients have to refer this contract explicitly. Explicit contracts lead to intention revealing and this is a good thing!

Conclusion

So in my opinion EBCs have benefits as well as shortcomings. I think they are worth investigating and knowing them, but at the moment I don’t see that they will establish well and become a replacement for IBCs. First there is the higher complexity, which could perhaps be solved by tools and some sort of „DI container“ for EBCs in the future. But second, being explicit and define formal contracts through explicit interfaces is no bad thing. Of course it’s not cheap as well, but I don’t see that this justifies the application of EBCs on the small scale. On the big scale there are other solutions like BizTalk, NServiceBus etc. to achieve the goal of pluggable components which have features like scalability as well. So perhaps there are delimited scenarios for using EBCs (like component topologies that change often), but I would not suggest to use them in general.

kick it on DotNetKicks.com

Rx: Event composition – single-valued

In a first blog post on the topic „event composition with Rx“ I presented operators that take several event input streams and create a single output streams, whose elements contain values from each input event („multi-valued“ event composition operators). This second blog post instead treats “single-valued” event composition. Multiple streams go into those composition operators and one single stream comes out, where each element of the output stream matches exactly one event/value from any input stream!

Example solution, PPT slides and general information

In general, all introductory information on composition, description of the „multi-valued“ event composition operators and more bits-and-pieces can be found in my first blog post.

I’ve created a SL3 demo project where you can experiment with each composition operator. You can find the sourcecode (SL3 VS2008 project) here and the live demo on Windows Azure here.

The PPT slides that contain all diagrams of the composition operators can be downloaded here.
I would be glad if you could leave my name and/or the blog URL (www.minddriven.de) on every diagram.

Merge()

The operator Merge does serialization of all input event streams by firing an event everytime one of the input streams fires. The event/value of the output stream will be the same as the event/value on the input stream that has fired.

The following code shows the simple usage of Merge:

    var composition = 
        Observable.Merge(stream1, stream2, stream3);

And the following example flow diagram shows the behavior of the operator under this code. Note how the incoming events are written to the output stream in exactly the same order as they come in:
Rx Event Composition - Merge

Amb()

Amb comes from ambiguous and has the following semantics. If you combine several input event streams with Amb, the output stream will only contain the events from the input stream that fires first. The other input streams are not taken into account afterwards. That’s a kind of winner-takes-all-strategy and could be valuable in some situations.

Amb can be used as follows:

    var composition = 
       stream1.Amb(stream2).Amb(stream3);

And the following diagram shows an example composition situation. Note that stream 1 fires first and consequently Amb only forwards events from this stream:
Rx Event Composition - Amb

Concat()

Concat does (the name says it all) concatenation of the input event streams. But wait: how can this work? In fact Concat only works when you have finite event streams! On infinite streams, Concat watches the very first stream forever and the other streams don’t come to their turn. Thus use Concat on finite event streams, when serialization of the input streams in the right order is crucial.

The following code shows the use of Concat on three finite input streams:

    var composition = 
        stream1.Concat(stream2).Concat(stream3);

And here’s the concatenation done by this code in an example situation (the square brackets illustrate finite streams):
Rx Event Composition - Concat

Until()

The operator name says it all: Until forwards events from an input stream to the output stream until an event on a second stream occurs.

The following code shows the usage:

    var composition = 
        stream1.Until(stream2);

And the following diagram shows the behavior of Until on 2 streams based on this code:
Rx Event Composition - Until

WaitUntil()

Again the operator name speaks for itself: WaitUntil does not forward events from an input stream to an output stream until an event on a second stream occurs. From then on every event of the first input stream will be forwarded.

Here’s some code that shows how WaitUntil works:

    var composition = 
        stream1.WaitUntil(stream2);

And the following diagram shows WaitUntil’s behavior based on this code in an example situation:

Rx Event Composition - WaitUntil

That’s it again. I hope you finde this information useful. As in the blog post on multi-valued event composition, I want to encourage you to give me active feedback and to improve the examples and descriptions of the composition operators above. Thanks!

kick it on DotNetKicks.com

Rx: Event composition – multi-valued

In preparation of some presentation on the Reactive Extensions (Rx) last week I’ve investigated the composition methods for several event streams on the Observable class. What methods are existing and what are they doing? Let’s take a look…

This first blog post treats „multi-valued“ event composition in terms of multiple streams going in and one stream comes out, but each element of the output stream is composed by sub-elements from each input stream! There is a second blog post that treats „single-valued“ event composition as well.

Example solution

I’ve written a little SL3 application where you can discover the behavior of those composition operators. It builds on example code that first has been published by Paul Batum some months ago and extends his code with some more possibilities. I’ve hosted the SL3 on Windows Azure where you can test it directly:

Rx Composition Demo

You can download the sourcecode of the Visual Studio 2008 solution as well: [Event Composition Sourcecode (ZIP)]
All you need to run the solution is the latest Rx for SL3 build, Visual Studio 2008 and the Silverlight 3 SDK.

Powerpoint Sources

If you want to use my diagrams in your presentations or somewhere else, here is the source PPT file: [Rx Event Composition PPT]
I would be glad if you could leave my name and/or the blog URL (www.minddriven.de) on every diagram.

How to read the diagrams and code

The general visualization concept is taken from Eric Meijer’s PDC session about Rx. Thanks Eric for your great work!

Rx Event Composition - General Visualization

The visualization shows an Rx composing operator in the middle. On the left there are event input streams, on the right is the composed output stream. The order of the events on a timeline is from right to left: the most right event goes first into the operator and comes first out in composed form. This is visualized by the t1, t2, t3 and t1‚, t2‚, t3‚ points.

The sourcecode snippets below are kind of abstract. They only show how the operators are used. They are based on 3 streams stream1, stream2 and stream3. Those streams can be seen as general abstract event streams, no matter which datatype they’re really using.

Now let’s come to our multi-valued composition operators…

SelectMany()

The SelectMany operator should be known from LINQ on IEnumerable or others and is reflected by the from keyword in LINQ queries as well. It projects a foreach loop or several cascaded foreach loops, if you execute multiple SelectMany calls after another. Thus the order in which SelectMany is executed is relevant!

The same is true for SelectMany on IObservable. Take the following code:

var composition = 
    from element1 in stream1
    from element2 in stream2
    from element3 in stream3
    select new[] { element1, element2, element3 };

This is equal to the following direct use of SelectMany:

var composition = 
    stream1.SelectMany(
        element1 => stream2.SelectMany(
        element2 => stream3.SelectMany(
        element3 => Observable.Return(new[] { element1, element2, element3 }))));

With this code an example composition scenario could be:

Rx Event Composition - SelectMany

Note that the event order is crucial. The first event on every input stream is in the right order, thus yielding to a first composed event. The second event on input stream 2 first fires when the third event on stream 3 is fired. The resulting event in this case contains the first event from stream 1, since it retains the right event order.

CombineLatest()

CombineLatest is a very useful operator. It fires everytime when one input stream fires. Then the corresponding output stream contains the latest values/events from each input stream.

Here’s the code how to use the operator:

var composition = 
    stream1.CombineLatest(
        stream2, (element1, element2) => new[] { element1, element2 })
    .CombineLatest(
        stream3, (elements12, element3) => new[] { elements12[0], elements12[1], element3 }));

And an example composition follows:

Rx Event Composition - CombineLatest

Zip()

In comparison to CombineLatest and others the Zip operator doesn’t use any results from an event stream multiple times. However it builds a queue of the events on every input stream. When every input stream queue contains at least one event, the Zip composition operator fires. Thus it synchronizes events, whereas every event on an input stream is waiting for an event on the other input streams.

The following code shows the usage of Zip():

var composition = 
    stream1
        .Zip(stream2, (element1, element2) => new[] { element1, element2 })
        .Zip(stream3, (elements12, element3) => new[] { elements12[0], elements12[1], element3 });

And the following diagram shows an example composition. Note that no event is used twice in the output stream and compare this with CombineLatest and the other operators:

Rx Event Composition - Zip

Note that the last event on stream 3 has no „partner“ on the other streams and thus it doesn’t appear on the output stream in this example.

Also notice that Zip() is equal to Join() if used with a conjunction of all input event streams as parameter:

var composition = 
    Observable.Join(
        stream1.And(stream2).And(stream3)
            .Then((element1, element2, element3) => new[] { element1, element2, element3 }));

Join() – 2 out of 3

The Join operator can be used in many cases and is very flexible. The method Join() can take several event compositions as parameters. Everytime one composition fires, the whole operator fires. That said, if you create a conjunction of all your event streams, then the composed output stream will be equal to Zip().

But Join gives you more power and flexibility. One example is a „2 out of 3“-situation. Imagine you have 3 input streams and want Join to fire everytime when 2 input streams contain an event. This can be done by passing Join the appropriate partial compositions as shown in the following code:

var composition = 
    Observable.Join(
        stream1.And(stream2)
            .Then((element1, element2) => new[] { element1, element2 }),
        stream1.And(stream3)
            .Then((element1, element3) => new[] { element1, element3 }),
        stream2.And(stream3)
            .Then((element2, element3) => new[] { element2, element3 }));

This yields to the following resulting composition for example input streams:

Rx Event Composition - Join 2 out of 3

Again in this example, the last event on stream 3 has no partner and doesn’t appear on the output stream (due to an odd amount of events over all input event streams).

ForkJoin()

ForkJoin can be used if you want a composition to fire exactly once. When all input event streams contain at least one event/value, the ForkJoin operator fires with the first event on every stream. Afterwards it doesn’t react to any changes/event on the input streams again.

Here’s the code how ForkJoin can be used:

var composition = 
    Observable.ForkJoin(stream1, stream2, stream3);

And here’s the diagram of a composition example:

Rx Event Composition - ForkJoin

That’s it for now, guys. I hope it’s valuable for you. Since these are just my initial ideas on this topic, I’m reliant on your feedback. Together we could make all those descriptions even more useful.

kick it on DotNetKicks.com

Reactive Framework (Rx) – first look

During the last weeks I took some time to have a first look at the Reactive Framework. Here I want to share some impressions and information with you.

Rx: What is it about?

The Reactive Framework (Rx) has been developed at the Microsoft Live Labs and is another creation by Erik Meijer, the father of LINQ. Rx will be part of the upcoming .NET Framework 4.0, but is already included as preview DLL (System.Reactive.dll) in the sources of the current Silverlight 3 Toolkit. It’s used there to get some smoother Unit Tests to work.

The aim of Rx is to simplify/unify complex event-based and asynchronous programming by providing a new programming model for those scenarios. That’s very important in a world which becomes more and more async (Web, AJAX, Silverlight, Azure/Cloud, concurrency, many-core, …) and where present approaches (event-based programming with .NET events, Begin/Invoke) hit the wall. Program logic gets hidden in a sea of callback methods which leads to nasty spaghetti code. Those of you who are creating larger async programs know what I mean 😉

Basic ideas

The main concept of Rx is reactive programming and that’s not new at all. It involves a distinction of data processing methods into push and pull scenarios:

  • In a pull-scenario your code/program is interactively asking for new data from the environment. In this case the actor is your program while it pulls new data from the environment.
  • In a push-scenario your program is reactive. The environment in pushing data into your program which has to react on every new incoming data item (see illustration below). Reactive programs are ubiquitous: every event-handler (e.g. for UI events) is an example for a reaction in a push-scenario.

Reactive Programming

The guys at Microsoft got a very important insight which builds the fundament of Rx: there’s a dualism between the Iterator and the Observer pattern! This means that both patterns are essentially the same, if you dismiss their practical intentions for a moment.
With the Iterator pattern you get a sequence of data which is iterated in the pull-mode: the Iterator is the actor and asks the iterable object for data.
The Observer pattern can be interpreted equivalently: the environment pushes data into your program (e.g. through events), which has to react. As result with repeatedly fired events you get a sequence of data, which makes the relationship to the Iterator pattern obvious.

With this, an Observer in the push-scenario is equal to an Iterator in the pull-scenario and that’s the key insight, which has led to the development of the Reactive Framework. 14 years had to pass from the publication of the GoF Design Patterns book until now to figure out this intense relationship of the Iterator and the Observer pattern.

LINQ to Events

Rx realizes the Observer pattern with the two interfaces IObserver and IObservable which are the pendants for IEnumerator/IEnumerable of the Iterator pattern. IObservable is a sort of „asynchronous collection“, which represents the occurrence of a certain event at different points in time. Thus it expresses a sequence of data, on which you can run arbitrary actions. In fact IObservable for push-scenarios is essentially the same as IEnumerable for pull-scenarios.

The interplay of IObservable and IObserver is the following: on an IObservable you can register (Subscribe()) an IObserver (Note the dualism to IEnumerable/IEnumerator here!). The IObserver has three methods OnNext(), OnCompleted() and OnError(). These methods are invoked when the IObservable gets new data, completes the data sequence or results in an error. Thus your IObserver implementations take care of the data processing which replaces your custom callback methods.

The real impressing thing with Rx is that with events as data sequences you can use LINQ syntax to process and transform these data sequences (that’s why it’s sometimes called LINQ to Events). To create instances of IObservable and for providing LINQ methods, Rx comes with the class Observable. If you want for example take the first 10 click events on a button but skip the first click, you could easily write:

Observable.FromEvent(button1, "Click")
    .Skip(1)
    .Take(9)
    .Subscribe(ev => MyEventAction(ev));

Subscribe() has some overloads. In this example I’ve directly specified an action which is executed when an event (= a piece of data) comes in. Instead you could give it e.g. your custom implementations of IObserver as well.
LINQ gives you real power in processing, composing and transforming your events as data stream. Even in the simple example above, if you would implement it by event-based programming without Rx, you would need some additional effort. You would have to use temporary variables to skip certain elements, take others and so forth. In general, more complex cases require complete finite state machines which can be circumvented with Rx.

Composing events with LINQ is another typical and impressing example for Rx. Thus, a dragging event on a textblock can be implemented as:

IObservable<Event<MouseEventArgs>> draggingEvent =
    from mouseLeftDownEvent in Observable.FromEvent(textBlock1, "MouseLeftButtonDown")
    from mouseMoveEvent in Observable.FromEvent(textBlock1, "MouseMove")
        .Until(Observable.FromEvent(textBlock1, "MouseLeftButtonUp"))
    select mouseMoveEvent;
draggingEvent.Subscribe(...);

In this example, with the from keyword the two events "MouseLeftButtonDown" and "MouseMove" are chained together. Everytime the left mouse button is pressed on the textbox, the „gate“ opens to react on mouse move events. The „gate“ closes again when the left mouse button is released. So the composed stream includes all events where the left mouse button is pressed and the mouse is moved – the typical dragging event!

There are other possibilities to compose events, which for example consider the order of events differently. Those build the interesting parts of the Reactive Framework and clarify the use cases, where Rx has real advantages over present event-based .NET programming.

Bottom line

Personally I like the new way of thinking of events as data sequence! The dualism of the Iterator and the Observer pattern has nothing artificially constructed, but some sort of purity and mathematical elegance for me. But one big question remains: do we need this in our everyday’s developer life and which advantages come with it?

Erik Meijer himself says about Rx:

Of all the work I’ve done in my career so far, this is the most exciting. […] I know it’s a bold statement, but I really believe that the problem of asynchronous programming events has been solved.

That’s a really strong message and it has some important weight since Erik is the creator of LINQ and has a big expertise in language design. Does Rx hold what he promises?

In my opinion Rx is really beautiful and valuable when you do complex asynchronous operations, where you have to compose and orchestrate events/data from several sources. With Rx you’re able to chain and filter events to easily create the concrete event, to which you want to react. That’s the power of LINQ, which allows transforming the resulting data as well. LINQ gives you the whole flexibility of processing the data stream that you already know from LINQ to Objects (on IEnumerable) etc.

Beyond that at the moment I don’t see a real big impact in many current development scenarios. If you have to handle simple events or do simple async computations, you are still fine with the present event-based programming model. Of course with Rx you can write your own observers to prevent a sea of callback methods, but encapsulation of handler logic can be done without that as well. Thus at the end I like the concepts of Rx (Observer, LINQ, …) and I’m curious to see how this whole thing develops after the release of .NET 4.0, but I’m not over-enthusiastic at the moment.

Links

Finally here is a list of links to some interesting websites regarding the Reactive Framework:

kick it on DotNetKicks.com