Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive programming with Javascript

I m new in reactive programming and I m a bit lost reading all these articles that I can't understand.

Actually, I m a javascript developer from Nodejs, Angularjs, Angular 2 and React.

What I do

I use promises all the time, for remote data fetching, local async resolution etc... Better testability than callbacks and fit my needs.

What I understand using streams

I can't figure out where streams can save me except in a particular case.

This special case, is that I can't use promises while listening on streams because the promise would be resolved only once.

An example with SocketIo:

io.on('connection',  (socket) => {
  // this works
});

io.on('connection').then((socket) => {
  // this can't work, promise would be resolved only once
});

If I m not wrong, I could use reactive streams to manage this case by simply returning an observable. Right ?

What I don't understand

I m studying Angular 2 and all the stuff around. Actually, from many blogs, people use to use observables to fetch remote data and I can't understand what could be an advantage of using it instead of promises.

The fact is that I would need to make a remote like in both cases, so why more one than the other ? Is this a performance issue ?

What I need

If you've read the whole question, what I need is to understand what are the advantages of using reactive programming instead of promises in the case of remote data fetching ?

In which (other cases) could it be better to use reactive stuff than usual stuff ?

like image 473
mfrachet Avatar asked Mar 14 '16 07:03

mfrachet


Video Answer


2 Answers

@Günter gave you the foundations of observables especially the ability of promises to be called.

To go a bit further, I think that the key advantage of observables is the ability to build an asynchronous data flow / stream using operators.

Here are some concrete use cases:

  • debounceTime / switchMap. When you want to leverage a form input to filter a list based on corresponding HTTP requests, the value you need to use for the request is the one when the user has finished to write. It's not necessary to send several requests: one per new characters (one for 's', one for 'so', one for 'som', ..., one for 'something to search'). The debounceTime operator allows this by buffering events and provides the last one after an amount of time of inactivity.

    Here is a sample:

    @Component({
      (...)
      template: `
        <input [ngFormControl]="ctrl"/>
      `
    })
    export class MyComponent {
      constructor() {
        this.ctrl = new Control();
        this.ctrl.valueChanges
                   .debounceTime(500)
                   .distinctUntilChanged()
                   .switchMap((vallue: string) => {
                     // Get data according to the filled value
                     return this.service.getData(entry);
                   })
                   .subscribe(data => {
                     // Update the linked list
                     this.list = data;
                   });
      }
    }
    

    If you only use switchMap, you will have one request per input but previous in-progress requests will be canceled. This allows you to get the correct result especially if request execution times is longer for some requests.

    In this case, you can link the event from the Web UI (DOM events) to HTTP requests to execute accordingly (react on events) and apply some advanced behaviors.

  • Implement retry. By mixing retryWhen, delay and timeout operators, you can easily (and transparently) implement retries

    searchPlaces(searchText:string) {
      var params = new URLSearchParams();
      params.set('placename_startsWith', searchText);
      params.set('username', 'templth');
    
      return this.http.get('http://api.geonames.org/postalCodeSearchJSON',
          { search: params })
        .retryWhen(error => error.delay(500))
        .timeout(2000, return new Error('delay exceeded'))
        .map(res => res.json().postalCodes);
    }
    

I think that this is the real power of observables: the asynchronous processing chain / data flow and linked different parts of the application based on events. It's something that can't be done with promises and allow to implement use cases to make your application more robust.

Here is a series of articles that could give you more details:

  • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html
  • http://slides.com/robwormald/everything-is-a-stream
  • https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
like image 98
Thierry Templier Avatar answered Oct 06 '22 18:10

Thierry Templier


Basically if you have a single async event you wan't to get notified about (callback) you use a Promise. If you expect a series of events use Observable

Advantages of Observable over Promise

  • Observable can be canceled
  • Observable are lazy (don't do anything before being subscribed to)
  • Observable can do what Promise can but only using Observable allows you to code the same way (using rx operators instead of .then() no matter if you expect one or a series of events.
like image 37
Günter Zöchbauer Avatar answered Oct 06 '22 19:10

Günter Zöchbauer