Blog

  • Angular Promises vs Observables

    Posted by Vinay Tiwari | Last Updated: 07-Dec-18

    In this blog, we will learn about the difference between promises and observables. there are some differences between promises and observables.

    A Promise emits a single event when an async activity finishes or fails.

    An Observable is like a Stream (in many languages) and permits to pass at least zero or more events where the callback is required for every event.

    Frequently Observable is preferred over Promise since it gives the highlights of Promise and more. With Observable it doesn't matter if you need to handle 0, 1, or various events. You can use the similar API for each case.

     

    Promise: 
    promise emits a single value


    For example: 

    const numberPromise = new Promise((resolve) => {
        resolve(5);
        resolve(10);
    });
    
    numberPromise.then(value => console.log(value));
    // still prints only 5
    

     

    Observable: 
    Emits multiple values over a period of time

     

    For example:

    const numberObservable = new Observable((observer) => {
        observer.next(5);
        observer.next(10);
    });
    
    numberObservable.subscribe(value => console.log(value));
    // prints 5 and 10
    


    we can think of an observable like a stream which emits multiple values over a period of time and the same callback function is called for each item emitted so with an observable we can use the same API to handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.

     

    Promise: 

    • A promise is Not Lazy
    • A Promise cannot be cancelled

     

    Observable: 

    • Observable is Lazy. The "Observable" is slow. It isn't called until we are subscribed to it. 
    • An Observable can be cancelled by using the unsubscribe() method
    • An addition Observable provides many powerful operators like map, foreach, filter, reduce, retry, retryWhen etc.

     

    Thanks

Tags: AngularJS