Angular 2 Observables

Angular 2 Observables

Observables help you manage asynchronous data. Think of it as AJAX for Angular 2. To use observables, Angular utilizes a third-party library called Reactive Extensions (RxJS).

Observer pattern

Because Javascript is single-threaded, handling async data streams are challenging. We utilize the Event Loop to determine the order events are executed.

The observer pattern is a perfect solution to utilize the event loop without occupying javascript’s single-thread. If you’ve worked with Node, you’re probably familiar with the event emitter pattern, which is a type of Observable.

In short, observables work as follows:

  • An object has dependents called observers
  • The object notifies the observers of state changes
  • The Event loop handles event

So why do we have to switch to RxJS if there are other observable patterns like Promises??

RxJS

Angular 2 is based on the idea of reactive programming. That means it works be detecting changes and reacting accordingly. Enter RxJS.

RxJS is great at working with complex data. It takes data and puts in into a stream. It’s also cancellable and cleans up after itself (what a nice library). That makes it a cleaner solution than using a promise or fetch.

 

Tags:
No Comments

Post a Comment