An Observable<E>
can emit zero or more values of type E
. The E
typed values can be mouse click events, price updates on a stock, etc., and are emitted until the observable stream completes or errors out.
The Observable
does not have to complete or error out. Both are optional and mutually exclusive. If the Observable
errors out it cannot complete and if it completes it cannot error out.
Both completion and erroring out end the Observable<E>
lifecycle, and no more values will be emitted.
Demo
In the below demo we use of
to create an Observable<string>
of the greeting Hola!
.
With this subscription it logs Hola!
and completes:
let emitAndComplete: Observable<string> = of("Hola!");
const subscription: Subscription = emitAndComplete.subscribe(
greeting => console.log(greeting),
() => console.log("Oh oh - we received an error"),
() => console.log("Finito!")
);
With this subscription it logs the error, and neither emits or completes:
let catchMeIfYouCan: Observable<string> = throwError("Catch me if you can");catchMeIfYouCan.subscribe(
() => console.log("Next handler will not execute"),
e => console.error(e),
() => console.log("Completion handler will not execute")
);