Observable

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code.

by Hemant Sharma

HTML

<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.js"></script>
<p>Open console and click on button to see how observable works. How we can subscribe and unsubscribe them.</p>
<button>Click</button>

CSS

button{
  background: Dodgerblue;
  color: white;
  border: none;
  padding: 10px;
  font-weight: bold;
  border: 1px solid Dodgerblue;
}
p{
  font-family: "Arial";
}

JavaScript

var button = document.querySelector('button');
var observer = {
	next: (value)=> {
  	console.log(value);
  },
  error: (error)=> {
  	console.log(error);
  },
  complete: () => {
  	console.log('Completed');
  }
}
/* Using its function fromEvent */
//Rx.Observable.fromEvent(button, 'click').subscribe(observer);
/*** Creating observable from scretch ***/
var subscription = Rx.Observable.create((obs)=>{
	/*
  obs.next("A first value");
  //obs.error("Error");
  setTimeout(()=>{ obs.complete(); }, 3000);
  obs.next("A second value"); // wont excute once completed or error comes
  */
  // How native fromEvent works
  button.onclick = (event) =>{
  	obs.next(event);
  }
})
.subscribe(observer);

//setTimeout(()=> { subscription.unsubscribe(); }, 5000);