What is reactive programming for?

I've read what is Reactive Programming?. The answer sounds good, but it's theoretical. I understand what it is, but I don't know what to do with it.

Where should it be used?

Have a simple example?

What is the concrete mechanism used for this to work? Concrete as far as it can be, I understand that in programming everything is abstraction except the excited electrons:)

Only works between local agents or one of them can be remote? Is it because of the internet?

Only works if it is something "smart, interconnected in parallel, nonlinear? If it is, what is this smart?

Apparently has to have robustness to be classified like this? Need to run on multiple servers? Or is it an option?

Is it a paradigm? Is it a framework? Can I use in .NET?

Author: Artur Trapp, 2017-07-31

3 answers

What is reactive programming for?

Reactive programming comes to our rescue in situations where the normal flow would be stopped by an error insert the description of the image here or for a delayed response time due to the amount of static cores among other specifications involved in their pillars. Summing up, to understand what it is for, it is necessary to understand its pillars.

insert the description of the image here

Here is a good summary of them .

Resilient: reacts to failures; applications react and recover from software, hardware, and connectivity failures;

That is, in the event of a failure, the application would have the intelligence to perform an action without user intervention. One scenario would be the call of a remote service: imagine that on a given call to that service does not respond, so an exception of time out will be thrown in a normal scenario. Already in reactive programming, an action would be taken so that somehow the fault is fixed, for example: wait x minutes and try again.

Message Driven ; a message-driven architecture is the basis of reactive applications. A message-driven application can be event-driven, actor-based, or a combination of the two.

An event-based system is based on events that are monitored by zero or more observers. This is different from programming not reactive, because the caller does not need to block waiting for a response from the invoked routine. Events are not directed to a specific address, but are seen (or heard).

Actor-based concurrency is an extension of the message passing architecture, where messages are directed to a recipient, who becomes an actor. Messages can cross thread boundaries or be passed to another actor's mailbox on a physical server different. This allows for elasticity-scaling demand-as actors can be distributed across the network, yet communicate with each other as if they were all sharing the same JVM.

The main difference between messages and events is that messages are directed while events happen . Messages have a clear destination, while events can be observed by zero or more observers .

Responsive: a responsive system is fast to react to all users (under good conditions or not) to ensure a rich and consistently positive "real time" user experience.

The speed and positive user experience in various conditions, such as the failure of an external system or a surge of traffic, depends on the two traits of a reactive application: resilience and scalability . A message-driven architecture provides the overall basis for a responsive system.

Why a is message-driven architecture so important for responsiveness?

The world is asynchronous. Here is an example: you are about to prepare a coffee, but you realize that you are without cream and sugar.

One possible approach would be:

  • start brewing coffee.
  • go to the store while the coffee is brewing.
  • buy cream and sugar.
  • go home.
  • drink coffee immediately.
  • enjoy life.

Another possible approach:

  • go to the store.
  • buy cream and sugar.
  • go home.
  • start brewing coffee.
  • patiently Observe the coffee as it is made.
  • try the coffee.
  • enjoy life.

As you can clearly see, a message-driven architecture provides an asynchronous boundary that will decouple you from time and space .

Elastic: reacts to demand / load: applications can make use of multiple cores and multiple servers;

A scalable system is easily upgraded on demand to ensure responsiveness under various load conditions.

Or Akka. Net approaches these subjects very well in an author's form, where in the event of a spontaneous increase in access to a server, its management is almost automatically or in the event of some failure in a of the authors a decision and made by the author who made the call.

Here has a good demonstration of the author's use of akka.

Now the questions.

Where should it be used?

The most used scenario I have seen is in application with large volumes of calls and sudden changes of accesses, but nothing prevents it from being used in any other system.

Have a simple example?

On the website of akka.net it addresses several concepts of how to implement.

What is the concrete mechanism used for this to work? Concrete up to where it can be, I understand that in programming everything is abstraction except the excited electrons:)

As mentioned in the other answer. One of the mechanisms is the Observer, the stream of Akka.net and Polling, take the same approach, although I still don't see the full approach.

No akka.net one of the concepts used is that of authors where a follow-up on the activities of an application and monitored by a supervisor, each subordinate pass on to his supervisor what is happening to him, in the occurrence of a failure a response and passed on to the supervisor and an action is taken according to the failure.

Only works between local agents or can one of them be remote? It is by cause from the internet?

Encompasses both scenarios, both can be applied in local agent and remote, (it is because of the internet), many changes occur by the blessed internet (save internet) and one of them is yes reactive programming.

Apparently has to have robustness to be classified like this? Need to run on multiple servers? Or is it an option?

No, it can be a simple application.

Is it a paradigm? Is it a framework? Can I use in .NET?

Are patterns that can be implemented with .NET yes, as previously talked about libraries POLLY.NET, AKKA.NET. akka can be used in C#, Java, etc.

Summarizing; Reactive programming, enable applications that are more available, faster and more reliable, able to self-recover and manage themselves.

With the help of tools such as Akka, Polly, WebSockets, DynamoDB, EC2, Autoscaling and messaging services (SQS, SNS, SWF). we can build reactive applications with relatively low effort.

 20
Author: Marco Souza, 2019-09-24 12:00:11

Many people mix the terms and concepts of reactive programming and of Reactive Systems , perhaps due to the Reactive Manifesto . In January 2017, Lightbend published a whitepaper that explains the two concepts and their key differences.

This answer is based on the concepts of reactive programming.


Where should it be used?

Can be used in several places. From a consultation to a "local" database, through monitoring the pointer on a screen, to distributed systems that handle a large number of requests per second.


Have a simple example?

Observing mouse movement in Silverlight:

var mouseMove = Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove");
mouseMove.ObserveOnDispatcher()
         .Subscribe(args => Debug.WriteLine(args.EventArgs.GetPosition(this)));

Source


What is the concrete mechanism used for this to work? Concrete up to where it can be, I understand that in programming everything is abstraction except the electrons excited:)

One of the mechanisms used is the GOF Observer pattern.


Only works between local agents or can one of them be remote? Is it because of the internet?

Part of the premise of reactive programming is to break down a problem into small steps that can be executed asynchronously and non-blocking. This problem can be divided between local and remote agents.

The Internet can be considered as a factor that leads to the adoption of reactive programming, since querying remote systems is a blocking operation that can affect the scalability of your system.


Apparently has to have robustness to be classified like this? Need to run on multiple servers? Or is it an option?

No. Reactive programming is on the rise in the world of Android apps, for example. Many developers are adopting this paradigm for the facilities it ends up with bringing and also by the characteristics of the platform.


Is it a paradigm? Is it a framework? Can I use in .NET?

Is a paradigm. And there are libraries and toolkits that implement this paradigm. An example for .NET are the Reactive Extensions.

 30
Author: Leonardo Lima, 2017-08-18 10:36:37

the answer was elaborated without focusing too much on the pillars of reactive programming, I left a dedicated section to explain how each of the pillars maps to each of the points of my answer

Definition of reactive

Before explaining what reactive programming is I think it is worth explaining what is the meaning of reactive in infopedia

That reacts.

That is, something that happens as a result of a previous event / event

Reactive Programming

If the concept of reactive programming exists, then there is also the concept of non-reactive programming. I will demonstrate both with the following code:

//Programção não reativa

console.log(prompt('Introduza um texto'));

//programação reactiva

function userInput(msg, action){
  action(prompt(msg));
}

userInput('Introduza um texto', console.log);

There is a subtle difference in code snippets. The first can be described as follows:

Opens a window for the user to enter text the user enter text the text that the user entered is written in the console

While the second can be described as follows

When the user writes the text in the window, write the text in the console

With this example you come to the conclusion that whenever you use callbacks you are programming reactively.

You no longer have a continuous instruction flow line in your code. Instead you will use and abuse the callbacks to establish what happens when a certain operation is completed .

Reactive programming with events

If you have ever worked with user interface then it is almost certain that you have already used reactive programming.

For example, when you add a handler to a one-button event you are stipulating what happens when the user clicks the button.

This is a particular example of the use of callbacks discussed above.

In fact this practice is so well known that there is a paradigm of its own for this way of programming. It is known as event-oriented programming

Reactive Programming and long-running operations

Another place where it is common to see the use of reactive programming is in long-running operations, especially if they have an asynchronous interface. One of the best known among programmers are the AJAX requests.

I leave here an example similar to one of the above questions.

var now = performance.now();
var request = new XMLHttpRequest();

request.onreadystatechange = function A() {
  if (request.readyState == 4 && request.status == 200) {
    console.log("API SE " + ~~(performance.now() - now) + "ms");
  }
}

request.open('GET', 'https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow', true);
request.send();

Once again the callbacks appear, you specify which code you want to execute when the request is satisfied by the server and the response reaches your program.

Reactive programming all in 1

If you have come this far you must be thinking that after all you have already programmed reactivamete and yes practically we've all done it.

The novelty now lies in frameworks that try to provide you with generic APIs to program reactively. More particularly the framework Reactive , available on multiple platforms

This framework brings together 3 functionalities in a single API.

  • events
  • data
  • asynchronous and or parallel processing

If I'm allowed I'd like to make a parallel to language C# and platform .NET. Basically the framework joins events with Task and with IEnumerable with their respective methods Linq and some extras.

In particular this framework takes special care when it comes to handling events. Even with a small number of events it is possible that you need several ways to process them, namely in relation to the order of the events and the possible possibility of existence of failures.

The API already provides you with a set quite satisfactory of possibilities but there will be cases where you should take extra care to know if really the events are happening in the order you want, at least that was my experience. You can take a look at the framework diagrams, I leave here one:

insert the description of the image here

I would like to leave here two examples of using this framework in C# that have already been useful in a professional environment and are relatively simple to understand.

File Viewer in a directory

public IObservable<FileSystemEventArgs> Watch(string path, bool includeExistingFiles = false)
{
    var watcher = new FileSystemWatcher(path, "*.*");
    watcher.IncludeSubdirectories = true;


    var observable = Observable.FromEventPattern(watcher, "Created")
        .Merge(Observable.FromEventPattern(watcher, "Deleted"))
        .Merge(Observable.FromEventPattern(watcher, "Changed"))
        .Merge(Observable.FromEventPattern(watcher, "Renamed"))
        .Select(a => a.EventArgs as FileSystemEventArgs);
    if (includeExistingFiles)
    {
        var currentFiles = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
            .Select(f => new FileSystemEventArgs(WatcherChangeTypes.Created, Path.GetDirectoryName(f), Path.GetFileName(f)));
        observable = observable.Merge(currentFiles.ToObservable());
    }
    watcher.EnableRaisingEvents = true;
    return observable;
}

Running a process and returning an observable

public IObservable<EventArgs> ExecuteProcess(string path, string parameters)
{
    var process = new Process() {
        StartInfo = new ProcessStartInfo(path, parameters)
        {
            UseShellExecute = false,
            CreateNoWindow = true,
        },
        EnableRaisingEvents = true
    };
    var observable = Observable.FromEventPattern(process, "Exited")
        .Select(a => (EventArgs)a.EventArgs);

    process.Start();
    return observable;
}

Reactive programming completion.

I don't know where @Yonathan went to get the pillars of reactive programming , but nevertheless they seem to me to be totally valid:

  • elastic : reacts to demand / load: applications can make use of multiple cores and multiple servers;
  • resilient : reacts to failures; applications react and recover from software, hardware and connectivity failures;
  • Message Driven: reacts to events ( event driven ): instead of composing applications by multiple threads synchronous, are composed of asynchronous and non-asynchronous event handlers blockers;
  • responsive : reacts to users: applications that offer rich and "real-time" interactions with users.

If you have followed the answer so far you know that all this is true.

Is message driven because you say when do.

Is responsive because it only makes the operation is complete (does not block)

Is resilient. At least Reactive has an extension, which allows you to try to run a number of events. time.

Is elastic. At least in the .NET framework you decide for yourself how many threads the framework should use .

Answering other questions of yours

Is it a paradigm?

A wikipedia says yes, emphasis mine.

In computing, reactive programming is an asynchronous programming paradigm

I'd just like to add that in addition to the event-oriented programming already mentioned by me, reactive programming brings enough new elements to be considered a different paradigm. Remember the three features I mentioned: events, data, asynchronous and or parallel processing

Only works between local agents or can one of them be remote? It is by cause from the internet?

It's not because of the internet but because someone determined that there was a problem to solve. That I know there was nothing so far that would allow you to combine these three features in an elegant and easy to handle way.

Apparently has to have robustness to be classified like this? Need to run on multiple servers? Or is it an option?

If you paid attention to my answer I did not pay much attention to robustness and much less spoke on several servers.

I just mentioned that it may be possible, with framework reactive, to try to execute determined operation again, if it fails.

Reactive programming may or may not be used in distributed environments, the robustness will depend on how your distributed system is implemented as well as all the services that participate in it.

 16
Author: Bruno Costa, 2017-08-03 22:01:53