Reactive Programming in Angular

What is Observables?

Observables are data objects that stream data in array like fashion to open up a continuous channel of communication in which multiple values of data can be emitted over time. An observer can subscribe to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits.

What if Observer?

Observer is a handler for receiving observable notifications implements the Observer interface. It is an object that defines callback methods to handle the three types of notifications that an observable can send: next, error and complete. Next is a required handler for each delivered value. Error is an optional handler for an error notification. This error halts execution of the observable instance. Complete is an optional handler for the execution-complete notification.

// Create simple observable that emits three values
const myObservable = Observable.of(10, 20, 30);

// Create observer object
const myObserver = {
  next: data => console.log('Observer got a next value: ' + data),
  error: error => console.error('Observer got an error: ' + error),
  complete: () => console.log('Observer got a complete notification'),
};

// Execute with the observer object
myObservable.subscribe(myObserver);
// outputs
// Observer got a next value: 10
// Observer got a next value: 20
// Observer got a next value: 30
// Observer got a complete notification

What is the difference between Hot Observable and Cold Observable?

Cold observables are observables where the data producer is created by the observable itself. For example, observables created using the of, from, range, interval and timer operators will be cold. The data is created from within the observable itself, and there truly is not data being produced until the observable is subscribed to.

Hot observables, on other hand, have their data producer outside the observable itself. These observables are closing over external data producers. For example, observables created with the fromEvent operator for either user events (clicks, mouse moves,…) or WebSocket events are hot observables. The data is being produced regardless of if there’s a subscriber or not. If there’s no subscriber when the data is being produced, the data is simply lost.

What is the difference between Observables and Promises?

Observables are lazy, which means nothing happens until a subscription is made. Whereas Promises are eager; which means as soon as a promise is created, the execution takes place. Observable is a stream in which passing of zero or more events is possible and the callback is called for each event. Whereas, promise handles a single event.