RxJS – evolving reactive extensions for javascript

Observable types – if you read about them before they may sounds for you like:
– EventEmitter
– EventDispatcher
– EventDelegate

… but they the observable types are not related to any of those concepts.

Let’s start explaining the concept with some comparision to other known concepts:

a) a function – which is executable synchronous code which at the end returns a value

b) an enumerable – is a concept of giving you synchronously multiple of values

c) a promise – something what could give you a single value asynchronous way

d) an observable – is something like enumerable so it can give you multiple values, but in an asynchronous way

ANATOMY OF OBSERVABLE
a) creation (red marked code):

var randomNumbers = Observable.create(subscribeFunc);

b) subscription (blue marked code):

Observable.create((s) => {
   var i = setTimeout(() => {
        s.next(Math.random());
        s.complete();
   }, 1000);
});

c) disposal (green marked code):

Observable.create((s) => {
   var i = setTimeout(() => {
        s.next(Math.random());
        s.complete();
   }, 1000);

return () => clearTimeout(i);
});

An example of using Observable types:

var randomNumbers = Observable.create((s) => {
   var i = setTimeout(() => {
        s.next(Math.random());
        s.complete();
   }, 1000);

return () => clearTimeout(i);
});

randomNumbers.subscribe(x => console.log('1:  ' + x));

randomNumbers.subscribe(x => console.log('2:  ' + x));

 


The output for those two will be similar to:

> 1: 0.1242282301923872651

> 2: 0.8273682638473682912

 


Why we get two random different numbers here?

 

When we created and we subscribed to it with the first (‘1: ‘ + x) then we run subscriber for the first subscription which caused setTimeout … then we run subscribe function for the second (‘2: ‘ + x) subscription …. then eventually first setTimeout occurs for the first subscription (cause NEXT/COMPLETE)… and after half a second second subscriber executes .next/.complete.

So in short the whole process looks as following:

  1. Creation
  2. Subscription 1
  3. Subscription 2
  4. setTimeout (for the first subscription) occurs
  5. Next/Complete (for the first subscription)
  6. setTimeout(for the second subscription occurs)
  7. Next/Complete (for the second subscription)
  8. Terminate

Observable is a function, that when invoked, returns infinite amount of different values (as in the example) between now and the end of time. If you are more interested more deeply to learn about RxJS Observables types then try to start with this documentation on GH.

 

 

react_admin

Leave a Reply

Your email address will not be published. Required fields are marked *


*