piotrkabacinski
8/20/2017 - 12:39 PM

rxExample.js

const Rx = require('rxjs');

{

  const streamExample$ = Rx.Observable.create( observer => {

    const interval = setInterval(() => {
      observer.next(new Date());
    }, 500);

    setTimeout(() => {
      clearInterval(interval);
      observer.complete();
    }, 3000);

  });

  const callbackExample = callback => {

    if(typeof callback !== "function") throw ("Callback is not a function!");

    const interval = setInterval(() => {
      callback(new Date());
    }, 500);

    setTimeout(() => {
      clearInterval(interval);
      callback("Koniec callback-u!");
    }, 3000);

  };

  const promiseExample = callback => {

    if(typeof callback !== "function") throw ("Callback is not a function!");

    const interval = setInterval(() => {
      new Promise((resolve, reject) => {
        resolve(new Date());
      }).then(callback);
    }, 500);

    setTimeout(() => {
      clearInterval(interval);
      callback("Koniec promise-ów!");
    }, 3000);

  };

  streamExample$.subscribe(
    data => console.log("stream$: " , data),
    error => console.error(error),
    complete => console.log("Koniec streamu!")
  );

  callbackExample(data => console.log("Callback: ", data));
  promiseExample(data => console.log("Promise: ", data));

}