Reactive Extensions in .NET Core

14 May 2021 at 10:00 by ParTech Media - Post a comment

It is a fast-moving world and things get updated quickly. Consider websites that show stock prices, live scores of sports events, or even a video streaming site. In all these cases, the data gets updated every second.

But have you noticed something? The data changes in the UI happen continuously and the users can see the change in real-time. It happens in the background so silently and that too without the page getting refreshed or reloaded.

It is being achieved through an asynchronous approach where there is a waiting and listening of the response data. In the meantime, the control is provided back to the user to browse the page. This approach of programming is called reactive programming. And the practice of implementing reactive programming in various programming languages is done using the reactive extensions that are available for the respective programming languages.

In this blog, we are going to look into reactive extensions and how to implement them in the C# programming language running on .Net Core.

Table of contents

  1. Introduction to Reactive Programming and Extensions
  2. Practical Implementation of Reactive Extensions
  3. Conclusion

Introduction to Reactive Programming and Extensions

Reactive programming is all about developing event-driven asynchronous applications which can communicate data between systems. It is achieved by creating data streams where they are responsible for communicating events, messages, calls, failures.

Let us explain this with an example. Consider two systems - services A and B. They communicate with each other. Now, A sends a request to B and the control call comes back to service A code (asynchronous approach). Now, a data stream (imagine a pipe of flowing water) has been established between these two services, and the requested data has been sent one after the other to the requesting service. The stream will be open until all the data is sent. It closes once a failure occurs. Also, it deals with variables that are time-sensitive. This means the value of the variables changes by reacting to the changes of its dependents.

To implement reactive programming in different programming languages, reactive extensions are available in multiple forms as external packages. So, the users need not worry about how to build a code for implementing reactive programming. Instead, they can concentrate on how to make the best use of reactive programming and get benefitted out of it.

Practical Implementation of Reactive Extensions

In this section, let's create a simple observable implementation in C# code. In this, the observable code prints certain data in the console window, but at the same it allows the users to type certain inputs in the same console window.

Step 1

Create a .Net Core-based console application and provide a valid name for it.

Step 2

Once the solution is created, the folder structure looks like below.

And the program.cs file looks like below. This is the file that will be modified to implement our changes.

Step 3

Right-click the project and go to Manage NuGet Packages. Search for reactive and install System.Reactive NuGet package.

Step 4

Go to the program.cs file and include using System.Reactive.Linq in the header section.

Step 5

Below is the code which needs to be included in the Program class. This, in turn, will be used to implement the required objective.

class Program

  {

​    static void Main(string[] args)

​    {

​      Console.WriteLine("Hello! This is from PARTECH.");

 

​      IObservable<string> observable = Observable.Generate(0, iterator => (iterator < 11), iterator => iterator + 1, iterator => new string('*', iterator), 

​        iterator => TimeSpan.FromSeconds(iterator));

 

​      using (observable.Subscribe(Console.WriteLine))

​      {

​        Console.WriteLine("Operation Started.");

 

​        Console.WriteLine("Press any key to exit!!!");

​         

​        Console.ReadLine();

​      }

 

​      Console.WriteLine("Operation Ended.");

​    }

  }

Here, Observable.Generate method is from the package System.Reactive package. Generate method has 6 overloads. We consume the method that accepts

  • the initial state of the loop variable,
  • loop to which the observable has to be executed
  • value to add over every iteration
  • the operation to do on each iteration,
  • the period with which the observable has to be executed (basically a scheduler).

Also, in the above code, we have placed the initial value of the loop as 0. The code will be looped 10 times, and it will be incremented by 1 for each loop. In the code, we are going to append the asterisk symbol in a pattern that goes like this - for the first loop it will have one asterisk, for the second two asterisk, and so on till 10 asterisks for the last loop of 10.

The asterisk will appear after an interval of the iteration number that is currently being executed. For example, the first asterisk will appear after one second, the second after two seconds, and so on.

But, it also provides the control to the user to key in any input data. The user does not need to wait till the process has been completed.

In the above example, the observables have been implemented and we have experienced how it works in the code. The reactive library has a lot more to offer along with the observables. It provides Subjects and Observer, which also comes in handy for asynchronous communication and for refreshing of data flowing between systems.

Conclusion

With the reactive extensions readily available to consume in .Net, it makes the application more responsive because of its asynchronous nature. It becomes easier for developers to implement the asynchronous and time-variant data update using the extensions.

Latest