Observable vs Subject vs Promise in Angular

 24-Aug-2018   nityaprakash     Angular  Angular4  Observable  promise  subjec    Comments  0

In this Article we are going to discuss about Observables, Subject and Promises in the Angular. We are going to talk about, what is Observable, Subject and Promise in Angular. How should create observable and subject? How it is different/similar with Subject and promise.

What is Observable?

In layman language Observable is data stream and method to act upon it. It is based on Publisher and Subscribe pattern. It provide support of event handling, asynchronous programming and handling events. It is actually declarative only and doesn't execute itself. It execute and start delivering data once it is subscribed by subscriber. It will keep executing until it is finished or unsubscribed by subscriber. As far as data delivery concern, it can deliver any type of value like, literal, messages,events.

Defining Observable in Angular

Observable have following components when it is declared.

Notification Type Description
next Required. A handler for each delivered value. Called zero or more times after execution starts.
error Optional. A handler for an error notification. An error halts execution of the observable instance.
complete Optional. A handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.

Creating Observable

In this example we are going to create a service which will return observable which emit a sequence of number.


export class DemoService {

  constructor() { }

  getSequence():Observable{
    var observableObj = new Observable(observer =>{
      observer.next(1);
      observer.next(2);
      observer.next(3);

      observer.complete();
    });

    return observableObj;
  }
}

Consuming the Observable.


ngOnInit()
  {
    this.demoSrv.getSequence().subscribe(n => { console.log(n)}, //Result for next
                                         error => console.log(error), //When error raise
                                        ()=>{console.log('completed')}); //When completed executed.
  }
  

We will pass three call backs to the subscribe method respectively for subscribe, error and completed. All three callbacks are not mandatory, only first one is mandatory to start publisher to notify. In this particular case output will look like below:

In this scenario, it is executing synchronously, we will use setInterval() to simulate asynchronous behavior.


export class DemoService {

  constructor() { }

  getSequence():Observable{
    var observableObj = new Observable(observer =>{
      var i:number = 1;

      setInterval( function(){
        observer.next(i);
        i= i+1;
        
        if( i == 21)
          observer.complete();
      }, 500);
    });

    return observableObj;
  }
}

Above code will execute iterate value of I in every 500 milliseconds, and mark it completed once it value reached to 21, once complete() or error() methods are called observable stop running. Observer has to subscribe again.

Error Handling in Observable

Because it is asynchronous, we can't handle with simple try catch method. Rather observable should call observer.error(message) method whenever observable to throw error. Observable will stop executing once error() method is called.


export class DemoService {

  constructor() { }

  getSequence():Observable{
    var observableObj = new Observable(observer =>{
      var i:number = 1;

      setInterval( function(){
        observer.next(i);
        i= i+1;
        
        if( i == 5)
          observer.error('Error thrown');
      }, 500);
    });

    return observableObj;
  }
}

See screenshot below when value of I is 5, it will call error() method, and stop executing.

Observable allows us to transform the value before it is delivered to subscriber. We can call return observableObj.pipe( map( n => n*2)). Subscriber will get values like 2, 4, 6, 8. Original method just iterating number but we can transform the value using pipe method.

Observable vs Subject

There are two concepts are play role here :

  • Data Producer
  • Data Consumer

We have seen earlier that data Observable produces the data and our component consume data by subscribing the Observable. Here is main difference between Observable and Subject. Subject can play both roles, data producer and data consumer. We can say it is a special type of Observable.


Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment

COMMENTS