Reactive Framework and IObserverable

Erik Meijer, the man behind LINQ is now come up with a framework called “Rx Framework” which contains API those decorates LINQ2Objects as mathematics dual.  Let us see in details.

LINQ2O and Mathematics Dual

Wikipedia says “A moprhism f:A->B is a monomorphism if  f.g=g.h implies g = h. Performing the dual operation, we get the statement that g.f = h.f  implies g = h. for a morphism f: B->A. This is precisely what is means for f to be an epimorphism. In short, the property of being a monomorphism is dual to the property of being an epimorphism.”

 LINQ to Objects is set of extension methods which enables to manipulate on a IEnumerable.  From a layman point of view, a collection is nothing but a data source from where we are pulling data using LINQ to Objects and/or ofcourse for…each.  From duality, this is f:A->B.

It is very common that we need to notify a data source when new items need to be added or existing item to be updated either.  The interaction is happened either sychronously, but in general asychronously.  Since, we are living in non-deterministic, disconnected programming world.

Updating a data source would be based on some user-interaction in an application through event.  Event is programming world idiom for asynchronous invocation, or if you take any non-user interaction application which is again based on “event” driven architecture.  This model is based on GoF’s observer pattern.

Observer Pattern

GoF says “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically”.

Observer Pattern

The observer those want to be notified whenever the subject undergoes a change in state should attach themselves with subject.  If you take button click event, we can write one or more event handlers.  Whenever a button clicked, it sends EventArgs to its subscribed observers (event handlers).

Introducing IObservable and IObserver

Let us  come back to the actual problem.  Since, IEnumerable can only be used to pull data from a data source as read-only i.e f:A->B, here A is data source and B is my IEnumerable.  However If I want  f: B->A which means that I would like to send/push data from “B” to “A”.  Here, I treat the callback or event handlers as “A” and the events as “B”.  It means that I need to push data to a data source as like as IEnumerable which is for pull.

As part of Reactive Framework, Meijar introduced two interfaces IObservable and IObserver.  Based on observer pattern, IObservable is source.  See the following figure.

IObserverable and Observer

The  Subscribe() method is used to register one or more IObservers for notification which is similar to Subject.Attach() in the observer pattern.  The IDisposable is .NET idiom which mimics Source.Detach().  To understand the fundamental objective of these objects think in reverse in place with IEnumerable.  To traverse through the IObservable, create an IObserver, give it to an IObservable, and the IObservable “pushes” data into the IObserver by invoking its methods.

OnNext() is used to iterate over data sources and push the argument “value”.  OnCompleted() is post-iteration handler.

An Example

Theory is enough.  Let us see an example in Silverlight 3.0.  I create a button with mouse move event which acts as IObservable and create a TextBox which acts as IObserver.  Whenver a mouse moved on the button, the textbox observer appends coordinates into TextBox.Text property.

To create a mouse move observable, I used System.Linq.Observable which is used to create IObservables.  I extend the System.Windows.Controls.Button with GetMouseMoves() which returns IObservableMouseEventArgs>> like the following:

public static class ButtonExtension
{
    public static IObservable>
      GetMouseMoves(this Button button)
    {
        return Observable.FromEvent((EventHandler genericHandler)
          => new MouseEventHandler(genericHandler),
            mouseHandler => button.MouseMove += mouseHandler,
            mouseHandler => button.MouseMove -= mouseHandler);
    }
}

 The FromEvent() overload takes three Action(s) as arguments. One to convert from a generic event handler (EventHandler) to MouseEventHandler.  Remaining two register/unregister.  For observers, I create a custom observer for handling mouse coordinates like

public class CoordinateObserver : IObserver>
{
    public TextBox CoordinateTextBox { get; set; }
 

    #region IObserver> Members

    public void OnCompleted()
    {

    }

    public void OnError(Exception exception)
    {

    }

    public void OnNext(Event value)
    {
        CoordinateTextBox.Text += (string.Format("Clicked at ({0},{1})\n",
          value.EventArgs.GetPosition(CoordinateTextBox).X,
          value.EventArgs.GetPosition(CoordinateTextBox).Y));
    }

    #endregion
}

I create an instance of CoordinateObserver and subscribes it to button’s GetMouseMoves()

rxButton.GetMouseMoves().Subscribe
  (new CoordinateObserver { CoordinateTextBox = this.rxResult });

The results would be

 The output

Download and Resources

Till now, there is no official release of Reactive Framework.  However, The Silverlight 3.0 Unit Test Framework uses this which comes as part of Silverlight 3.0 Toolkit.  Assembly Name: System.Reactive.dll, which unfortunately builds with Silverlight’s System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e.  See the following image:

Assembly

  1. First download Silverlight 3.0 Toolkit and install it.
  2. Extract source code from $Program Files$\Microsoft SDKs\Silverlight\v3.0\Toolkit\Jul09\Source\Source Code.zip.
  3. Get the System.Reactive.dll from $Source Code Folder$\Binaries.

The full source code of the example is available at https://udooz.net/index.php?option=com_docman&task=doc_download&gid=5&Itemid=5.

Mark this!
  • Digg
  • del.icio.us
  • Add to favorites
  • RSS