Author

Hi there!

I'm Anil Kumar M.S. A technology enthusiast living in Mysore, India. I'm Passionate about .Net, Web Apps, Cloud, Application design and Architecture, Ux, Javascript and Windows Phone.

A Microsoft Certified Technology Specialist and also a Professional Developer in .Net 4 Web. I like travelling, doing Adventure & Love food.

Let's be friends !



Webpage : www.msanil.com
×

Saturday, November 19, 2011

Introduction to .Net Reactive Extensions!

Saturday, November 19, 2011
The reactive extensions or Rx is just a library which developers can make use when writing asynchronous and event based programs using observable collections and with LINQ style query operators.
For a beginner, this is just one more library which extends .net and helps you when you write Async and Event driven code for your applications.

The Reactive extensions work for desktop as well as web based applications.


Simply, Imagine, there are few data streams from different sources like task status updates, Tweets, Emails, Resource Requests etc. Using Rx, you can represent/define these sources as Asnc Data streams and you can then subscribe to an event stream using the IObserver <T> interface.

The interface notifies/informs the the subscriber whenever an event occurs. (Say When a new tweet received, when a new resource request received etc, your piece of code can be triggered). Source data stream can be anything you can think of not just the ones i mentioned! (Say, when a Database Operation to get the data is completed, you will have a data stream. Above data stream examples are just small examples. You can imagine any piece of data that gets changed sometime as an data stream)

Subscription here is just like you subscribe for a weekly magazine by email and once the magazine is released every week, you will get an update to email.

The Observable Streams mentioned above are nothing but Data Streams. So, you get an option to query them using regular LINQ Queries in .Net. You can handle exceptions & Concurrency too.

How do you get this library?

Visit http://msdn.microsoft.com/en-us/data/gg577610 & Start checking out the downloads.

Well, if you are using .Net 4.0/Silverlight 4, then you already have it!!

If you are using 3.5, check out the stable release here http://go.microsoft.com/fwlink/?LinkID=220814
Install It.


Reactive extensions are also available for Windows Phone 7 & JavaScript too. Will write more about it in future.That was too much of theory and very complicated isn't it? Lets write some code now to understand.

First, to start with, let us see how Rx works with LINQ Queries but even before that let us see how normal LINQ Query works. In my case, i have Visual Studio 2010 with .Net 4.0.

Start Visual Studio &  Create a Console application. Let us take an example of creating a series of numbers in LINQ. The query would be 

var query = from num in Enumerable.Range(1, 5) select num;

The above query just fetches numbers from 1 to 5.  Here is how you execute and see the output. Complete listing below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Rext
{
    class Program
    {
        static void Main(string[] args)
        {
            // Query to Get Numbers from 1 to 5
            var query = from num in Enumerable.Range(1, 5) select num; 

            //Output each number to console
            foreach (var num in query)
            {
                Console.WriteLine(num); 
            }

            //Say the operation is completed
            Completed();

            // Do not close the console window after printing. Hold on.
            Console.Read();
        }

        /// 
        /// This method just prints some static text to console
        /// 
        static void Completed()
        {
            Console.WriteLine("Operation Completed.");
        }
    }
}
The above example when executed shows the below output.

Now, how do you achieve the same with Rx Extensions. First, convert the above linq query to a Observable Query. To do that,

Add a reference to System.Reactive in your solution. (Search program files if you could not find the dll already in references list of your project)

Write the below includes in your code
using System.Reactive;
using System.Reactive.Linq;

 // Query to Get Numbers from 1 to 5
            var query = from num in Enumerable.Range(1, 5) select num; 
            var ObservableQuery = query.ToObservable(); // Convert Normal Linq Query to Observable Query.

Then, Using Reactive Extensions, We can subscribe to ObservableQuery by calling the Subscribe method. The subscribe method expects you to pass the Function Name that is to be executed each time

when there is a result. Also, Optionally you can specify to call a method when the whole Operation is complete (LINQ Query is completely Executed).

In this case, i want to print every result to a Console so using a Console.Writeline and finally call the Completed() method written above. So, Code becomes
ObservableQuery.Subscribe(Console.WriteLine, Completed);
Here is the complete listing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive;
using System.Reactive.Linq;


namespace Rext
{
    class Program
    {
        static void Main(string[] args)
        {
            // Query to Get Numbers from 1 to 5
            var query = from num in Enumerable.Range(1, 5) select num; 
           
            //Convert the above Normal Linq Query to ObservableQuery
            var ObservableQuery = query.ToObservable();

            //Now, Subscribe to the Observable Query
            ObservableQuery.Subscribe(Console.WriteLine, Completed);

            // Do not close the console window after printing. Hold on.
            Console.Read();
        }

        /// 
        /// This method just prints some static text to console
        /// 
        static void Completed()
        {
            Console.WriteLine("Operation Completed.");
        }
    }
}
ok. what did we achieve now?
We just made the code compact. Instead of a foreach loop, this one line code of subscribing prints the result. When you run the code, you can see exactly the same result you saw earlier.

But, you may say this is just an alternative to forach loop. No, that's not all, you can do a lot but in this case, we are running everything on 1 thread. In my next post, we shall see how we can do the same operation on a entirely different thread!!

Author : Anil Kumar M.S
A technology enthusiast living in Mysore, India.
You can connect with me on Twitter @MSGuyTweets or on Facebook.
Email me at ms.anil.kumar@gmail.com


Was this post useful?