What is reactive programming for?

Asked

Viewed 2,697 times

55

I have read What is Reactive Programming (Reactive Programming)?. The answer sounds good, but it’s theoretical. I understand what it is, but with that I don’t know what to do.

Where it should 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 other than excited electrons :)

Only works between local agents or can one of them be remote? It’s because of the internet?

It only works if it is something "intelligent, interconnected in parallel, non-linear? If it is, what is this intelligent?

Apparently you have to have robustness to be classified like this? Do you need to run on multiple servers? Or is it an option?

Is it a paradigm? It’s a framework? I can use in . NET?

  • 18

    Excited electrons ( ° ʖ °)

  • 1

    This question is very good, and difficult to go into detail due to the complexity it involves the Patterns design, as described at the end of the answer to the other question. An example and the library of Polly that makes the application more Resilient. Many other technologies must be involved to have a Reactive Programming.

  • In a comment of the link you posted, the following link was indicated as the best material ever read by the user: https://github.com/kriskowal/gtor

  • @bigown I found your question interesting because I also didn’t know what it was exactly, so I went online and found this answer that I found interesting! https://answall.com/questions/55332/o-que-%C3%A9-reactive-Programming-program%C3%A7%C3%A3o-reactive

  • @Perozzo seems sensational, just so it’s worth the question.

  • @miltoncamara is in the question.

  • @Marconciliosouza there is at your discretion, I would like to see the answer.

  • @bigown now understood that you made a link with the answer you read rs.

  • @sensational mustache even, had never read about. I started reading now and found it very interesting.

  • you feel like putting an offering in this question to see if an adventurer appears who understands the subject.

  • @Marconciliosouza there is with you. Yours is good, but it would still be cool some other. Then I want to do others on the subject. I posted in the MVP group and I’m sure there is someone there who would give a great answer, but at the moment I only took one or the other who wanted to complain instead of helping, certainly there are others among the more than 100 with a more positive attitude, who knows one of them answer.

  • The discussion below is very rich and will add well to the theme. https://stackoverflow.com/questions/1028250/what-is-functional-reactive-programming

  • You should have opened a Bounty in the old question. Your question is a duplicate question.

  • 1

    @Brunocosta as it can be duplicated if what I’m asking is everything different, until I show that I read that. Just because the subject is the same is not the same. I can put one in this because so far it has good answers, but that still do not answer 100%.

  • I see this "reactive programming" as an excellent use of the Observer design principle. I have tired of implementing this at hand on the most diverse platforms of java (desktop, ee, android ...) and I confess that I missed something more standardized. Rxjava fell very well -> https://github.com/ReactiveX/RxJava

  • Have you found your answer ?

  • 1

    @Marconciliosouza I think not, I will wait a little, I will try to bring someone who answers

Show 12 more comments

3 answers

31

Many people mix the terms and concepts of reactive programming and of reactive systems, perhaps due to Reactive Manifesto. In January 2017, Lightbend published a whitepaper (in English) which explains the two concepts and their key differences.

This response is based on the concepts of reactive programming.


Where it should be used?

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


Have a simple example?

Watching the mouse move on 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 other than the excited electrons :)

One of the mechanisms used is the Observer Pattern from GOF.


Only works between local agents or can one of them be remote? It’s because of the internet?

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

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


Apparently it has to be robust to be classified that way? 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 bringing and also for the characteristics of the platform.


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

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

  • 2

    Reading the answer I had the impression that being reactive is applying the Observer standard, is that right? Is it no more complex than that?

  • 1

    Notice that I stated that the Observer standard is one of the mechanisms used. The Reactivemanifest lists several characteristics that applications must have in order to be considered reactive. Reactiveextensions, for example, extend the Observer standard and add the ability to flag errors and stream terminations.

  • @Leonardolima, cool his reply, his comment talks about signaling errors, but signal errors current schedules already do this, one of the pillars of reactive programming works on what is Resilient, I see nothing addressing on this in his reply.

  • 1

    @Marconciliosouza did not include in my reply because it was a direct enumeration of the questions of the original question (and the link originally indicated already touches on the subject). The commentary was a clarification on a misunderstanding, exemplifying with a feature of the cited library.

22


What is reactive programming for?

Reactive programming comes to save us in situations where normal flow would be stopped by an error inserir a descrição da imagem aqui or for a time-consuming response due to the amount of static nuclei among other specifications involved in their pillars. In short, to understand what it serves, it is necessary to understand its pillars.

inserir a descrição da imagem aqui

Here’s 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 the intervention of the user. A scenario would be the call of a remote service: imagine that in a given call to that service does not respond, so an exception of time out will be released in a normal setting. In reactive programming, an action would be taken to somehow correct the fault, 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 driven by events, based on actor 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 non-reactive programming, 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 rather are seen (or heard).

Actor-based competition is an extension of the messaging 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 different physical server. This allows elasticity - scaling demand - as actors can be distributed over the network, yet they 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 as events take place. Messages have a clear destination, while events can be observed by zero or more observers.

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

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

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

The world is asynchronous. Here’s an example: you’re about to make a coffee, but you realize you’re out of cream and sugar.

A possible approach would be:

  • Start making the coffee.
  • Go to the store while the coffee is getting ready.
  • Buy cream and sugar.
  • Come home.
  • Drink coffee right away.
  • Enjoy life.

Another possible approach:

  • Go to the store.
  • Buy cream and sugar.
  • Come home.
  • Start making the coffee.
  • Observe patiently the coffee as it is made.
  • Try the coffee.
  • Enjoy life.

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

Elastic band: 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.

The Akka. Net addresses these issues very well in an author form, where, in the case of a spontaneous increase of access to a server, its management is almost automatically or in case of any failure in one of the authors a decision is made by the author who made the call.

Here has a good demonstration of the author use of Akka.

Now the questions.

Where it should be used?

The most used scenario I have seen is in application with large volumes of calls and sudden changes of access, but nothing prevents to be used in any other system.

Have a simple example?

On the website of Akka.net various 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 other than the excited electrons :)

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

In 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 relays to his supervisor what is happening to him. In the event of a failure, a response is passed on to the supervisor and an action is taken according to the failure.

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

It encompasses the two 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 rather reactive programming.

Apparently it has to be robust to be classified that way? Need to run on multiple servers? Or is it an option?

No, can be a simple application.

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

They are standards that can be implemented with . NET yes, as previously talked about libraries POLLY.NET, AKKA.NET. Akka can be used in C#, Java and others.

In short; Reactive programming allows for more available, faster and more reliable applications capable of self-recovery and management.

With the help of tools like the Akka, Polly, Websockets, Dynamodb, EC2, Autoscaling and Messaging Services (SQS, SNS, SWF), we can build reactive applications with relatively low effort.

16

The answer was drafted 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 is reactive programming I believe it is worth explaining what is the meaning of reactive in infopedia

Reacting.

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 dialog for the user to enter text The user enter text The text you entered is written on the console

While the second can be described as follows

When the user type the text in the window, type 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 line of instructions flow continues in your code. Instead you will use and abuse the callbacks to establish what happens when a given operation is completed.

Reactive programming with events

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

For example, when you add a Handler for a one button event you are to stipulate what happens when the user clicks on the button.

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

In fact this practice is so well known that there is a paradigm for this form of programming. It is known as Event-oriented programming

Reactive programming and long-term operations

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

Let me give you an example similar to one of the 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 appear the callbacks, you specify what 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 programmed reactivates and yes virtually all of us have done it.

What’s new now is frameworks that try to provide you with generic Apis to reactively program. More particularly the framework Reactive, available across multiple platforms

This framework joins 3 functionalities in a single API.

  • Events
  • Dice
  • Asynchronous and parallel processing

If I may, I’d like to parallel the language C# and platform .NET. Basically the framework joins events with Task and with the IEnumerable with the respective methods Linq and a few extra.

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

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

inserir a descrição da imagem aqui

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

File observer 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 completion programming.

I don’t know where the @Yonathan has sought the pillars of reactive programming, but nevertheless seem to me to be fully valid:

  • Elastic band: 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 multiple applications threads synchronous systems are composed of asynchronous event managers and not blockers;
  • Responsive: Reacts to users: applications that offer rich interactions and "real time" 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 only the operation is complete (does not block)

It is resilient. At least Reactive has an extension, which allows you to try to hold event a number of times.

It is elastic. At least in the . net framework decides by Voce how many threads the framework should use.

Answering your other questions

Is a paradigm?

To wikipedia says yes, emphasis mine.

In computing, reactive Programming is an asynchronous Programming paradigm

I would just like to add that in addition to the event-oriented programming I mentioned earlier, reactive programming brings enough new elements to be considered a different paradigm. Remember the three features I mentioned: Events, Dice, Asynchronous and parallel processing

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

It’s not because of internet but because someone determined that there was a problem to solve. As far as I know there was nothing so far that would allow you to combine these three functionalities in an elegant and easy-to-handle way.

Apparently it has to be robust to be classified that way? 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 the reactive framework, to try to run certain operation again, if it fails.

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

  • I still want to reread, but I’ve seen that it’s very good, seems to have given to understand everything.

  • I only found myself in the middle subject of your response forward, your first example example for me does not demonstrate reactive programming only a new flow to be followed and not the possibility of another decision ( follow this if it does not work) I haven’t seen all the answers the question asks. From the middle to the end I thought it was cool.

  • here are the references used in the other question http://blog.andrefaria.com/programcao-reactive-programming

  • https://www.youtube.com/watch?v=h4zRhjSto8U&t=27

  • @Some questions were answered in the content and did not need to be answered again. In fact, I just didn’t answer two questions at all: Onde deve ser usada? and Qual é o mecanismo concreto usado para isto funcionar? (although I have spoken on the reactive Extensions). As I said in my reply the reactive programming consists rather in specifying quando do, although it may not be reactive programming was the simplest I found to illustrate what I meant to say.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.