Observable: An observable is a unique object just like a promise that that is used to manage async code. Observables are not part of the JavaScript language so the developers have to rely on a popular Observable library called RxJS. The observables are created using the new keyword.
See a simple example of observable to understand it better:
- import { Observable } from 'rxjs';
- const observable = new Observable(observer => {
- setTimeout(() => {
- observer.next('This is a message from Observable!');
- }, 1000);
- });
Observer: Any object that has to be notified when the state of another object changes is called an observer. An observer is an interface for push-based notifications delivered by an Observable.
See the structure of an observer:
- interface Observer<T> {
- closed?: boolean;
- next: (value: T) => void;
- error: (err: any) => void;
- complete: () => void;
- }
The handler that implements the observer interface for receiving observable notifications is passed as a parameter for observable as follows:
- myObservable.subscribe(myObserver);