Creating observables is only half the battle. Having a data source is one thing, but if nobody observes, listens, or watches, then it is pretty much useless. As a matter of fact, an observable will only be executed if there is at least one observer.
With RxJS, each subscriber is called Observer. These are listeners for the values emitted/produced by Observable.
Here's a basic example:
const observer = { next: (x:any) => console.log(`Observer got a next value: ${x}`), error: (err:any) => console.error(`Observer got an error: ${err}`), complete: () => console.log('Observer got a completion notification') };
Here, the observer object is a valid observer. As illustrated in the preceding code block, it should have three basic functions called next, error, and complete, which are part of the Observable API contract.
This contract is quite simple:
- next: Can be called 0-n times (that is, each time a new value is available)
- error: Can be called only once, then nothing else can be emitted through the observable (that is, called if an error occurs)
- complete: Can be called only once, then nothing else can be emitted through the observable (that is, called if no more values will ever be emitted)
Let's explore what this contract means in practice. Consider the following example:
observer.next(1); observer.next(2); observer.next(3); observer.complete(); observer.next(4); // 4 will not be delivered!
In this example, the next method of the observer is called multiple times. After that, the complete function is called once. After that, calling next again won't have any effect because the stream has been terminated.