Promises & Observables AngularJs.

So, What is an Observable?

  • Event emitter.

  • HTTP Modules.

  • The routers.

Angular makes use of observables as an interface to handle a variety of common asynchronous operations.

Sure M8, but how do we use them...

  1. Create an Observable instance that defines a subscriber function.

  2. Calls subscribe() method, passing an observer.

  3. The observer defines callback methods to handle the three types of notifications that an observable can send.

And that means?

A typical observable creates a new, independent execution for each subscribed observer. Then it wires up an event handler and delivers values to that observer. When a second observer subscribes, the observable wires up a new event handler and delivers values to that second observer in a separate execution. 

 

Then, Multicasting is the practice of broadcasting to a list of multiple subscribers in a single execution.

OH! so we use observables when...

  1. We want to work with multiple values over time.

  2. We need to cancel or retry them at some point.

  3. We want to work with operators (map, filter, etc).

  4. We want to make reactive calls.

Ok, then... We now can say

Observables offer a flexible set of ways for composing and transforming asynchronous streams.

 

They provide a multitude of functions to create streams from many other types, and to manipulate and transform them, read user input, perform asynchronous data fetches and set up custom emit/subscribe routines.

Promises Obsevables
Returns a single value.

Not Lazy, it calls services without then. and catch.

Not cancellable.

Doesn't provide operators.

More readable code with try/catch and async/await.
Works with multiple values over time.

Lazy, it's not called until we subscribe to it.

Cancellable using Unsubscribe().

supports map, filter, reduce and similar operators.

Use Reactive Extensions (RxJS).

An array whose items arrive
asynchronously over time.
Made with Slides.com