Learnitweb

Observer in RxJS

1. Introduction

An Observer is a consumer of values delivered by an Observable. Observable has callbacks for each type of notification delivered by an Observable: next, error and complete. A typical Observer object looks like the following:

let observer = {
  next: value => console.log('next value: ' + x),
  error: err => console.error('error: ' + err),
  complete: () => console.log('Complete notification'),
};

2. Using an Observer

To use the Observer, provide it to the subscribe of an Observable:

observable.subscribe(observer);

3. Partial observer

It is not mandatory for an Observer to have all three types of callbacks. If any type of callback is missing, it is still a valid Observer. If any of the three callbacks is missing then that type of notification will be missed. Following is an example of partial observer:

let observer = {
  next: value => console.log('next value: ' + x),
  error: err => console.error('error: ' + err),
};

While subscribing to an Observable, you may provide only the next callback as an argument without being a part of an Observer object, for example:

observable.subscribe(value => console.log('next value: ' + value));

Behind the scenes, it will create an Observer object using the next callback passed as the argument.