Saturday, July 22, 2017

Observable ABCs in the abstract

I am just over halfway through a series of online trainings on Angular 4 and it is starting to get into Observables. Today I learned some stuff so simple that there isn't really a praxis for it. Consider these imports:

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { Observer } from 'rxjs/Observer';

 
 

They will allow you to do something silly like this which will sequentially show you numbers counting up at the console:

const whatever = Observable.interval(1000);
whatever.subscribe(
   (numb: number) => {
      console.log(numb);
   }
)

 
 

Honestly, we didn't need Observer for what was immediately above, but let's loop that in now.

const fly = Observable.create((flyFu: Observer<string>) => {
   setTimeout(() => {
      flyFu.next('our fly is still alive after one second');
   }, 1000);
   setTimeout(() => {
      flyFu.next('our fly is yet still alive after two seconds');
   }, 2000);
   setTimeout(() => {
      flyFu.error('our fly has died');
   }, 3000);
});

 
 

Observer, which I had never heard of, lets me fake an asynchronous call against maybe a web socket as I never would. Yay! This naturally allows for:

fly.subscribe(
   (yes: string) => {
      console.log(yes);
   },
   (no: string) => {
      console.log(no);
   },
   () => {
      console.log('our fly is done');
   }
);

 
 

The three cases above are of course:

  1. getting something back from an Observer successfully
  2. an error handling scenario
  3. something to happen upon completion

 
 

...in that order. You will never see the completed scenario in running our code above. In order for that to happen the error jammed in a setTimeout would need to perhaps be changed up like so:

setTimeout(() => {
   flyFu.complete();
}, 3000);

 
 

Once the complete goes off there will be no further asynchronous activity. Expect no new successes or errors.

No comments:

Post a Comment