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
, andcomplete
. Each property is a function that returnsvoid
. - The
next
function receives avalue
of typeT
. - The
error
function receives anerr
of typeany
. - 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:
- Subscribe with no parameters.
- Subscribe with a partial
Observer
instance. - Subscribe by providing the callback functions in order:
next
,error
, and thencomplete
.
Note, when using the third approach, which is quite common, you can omit/skip any of the parameters by using either null
or undefined
.