Getting Started with Reactive Extensions

Hi Friends,

In Today’s section, we will talk about Rx library. Basically, Rx is a library for composing asynchronous and event based programs using observable collections. This is very useful in the cases where in you are pulling data asynchronously from different sources and then manipulating the same and finally printing the result. In these kind of scenarios, you have to write lots of glue code and off-course, these codes will be error prone as one of the sources if just throws error, then what will happen?

This way, you really need to do lots of stuff for the things working fine. Hence, Rx is answer to this kind of situation, which keeps the thing simple yet lightweight. Rx also uses LINQ query on the observable collections.

But, it would be nice to talk little about collections before starting Rx.  IEnumerables are one of the most widely used Pull Based collection which is synchronous in nature. Below is the sample snippet for the same.

And, let us suppose due to any reason, your datasource went down for some time, then what will happen? It will keep waiting until database comes online. And, you will land in a embarrassing something like shown below.

1st

And, you will end up doing something like this!

hang

However, you can convert the same Pull based interface to Push based interface. Below is the sample for the same.

Very complete, precise and stable. We will see few examples around the same in a moment. Below in the sample console app, you can see that IObservable and IObserver are available by default in .NET 4.0 and higher. 2nd Now, let me go ahead and install Rx extension from nuget. 3rd On successful installation, you can verify the assemblies. 4th Now, these are three phases of getting observables. 5th Let me explain the same with a simple demo. Now, as you can see in the below screen shot, as soon as i started creating observable, it started giving bunch of overloads which i can make use of. 6th

In the above snippet, I have mentioned comment on each line, what it is doing. Best thing with this is its asynchronous nature which you can see below in the output.

7th

Here, my program is executing on one thread and I am also typing on there on the same console, which means UI is not blocked. Its free for any activity. I hope, you would have liked this small example around Observables. We will delve more in coming sections. Till then, stay tuned and Happy Coding.

Thanks,
Rahul Sahay
Happy Coding

2,931 total views, 1 views today