LiveLoveApp logo

Observer Interface

Observer Interface

Now that we've learned the basics of creating a new Observable, or the producer of values, let's transition to the consumer of values, or the Observer.

To start with, let's look at the Observer interface:

interface Observer<T> {
  next: (value: T) => void
  error: (err: any) => void
  complete: () => void
}

Let's break this down:

  • First, the interface defines a generic type of T. This represents the type of values that are produced by the Observable.
  • Next, an Observer has three properties: next, error, and complete. Each property is a function that returns void.
  • The next function receives a value of type T.
  • The error function receives an err of type any.
  • Finally, the complete function is invoked without any parameters.

Observers are a set of functions for each type of notification that an Observable emits.

Let's look at the type definition for the subscribe method of the Observable class:

subscribe(observer?: Partial<Observer<T>>): Subscription
subscribe(next: (value: T) => void): Subscription
subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription

The subscribe() method of an Observable instance is overloaded to accept:

  1. Subscribe with no parameters.
  2. Subscribe with a partial Observer instance.
  3. Subscribe by providing the callback functions in order: next, error, and then complete.

Note, when using the third approach, which is quite common, you can omit/skip any of the parameters by using either null or undefined.