Observable in Angular
However, an observer or observable is a software paradigm constituting the design of an object which is called a subject that maintains a list of various dependencies that are called observers. These dependencies are automatically notified whenever you try to change states.
Nature of Observable
Observables in Angular are generally declarative i.e., if you ought to define a function for value publication. It won't be executed until and unless it is subscribed. The subscriber is termed as a consumer who receives the notifications until the function completes itself or until they manually unsubscribe.
An observable can be used to deliver any type of multiple values be it literal events, messages depending upon the context provided. The receiving and delivering values are synchronously or asynchronously the same. Since the setup and breakdown are handled by the observable, you don't need to worry about your application code being subscribed to consumer values or unsubscribed. Be it an HTTP response or a timer of intervals, the interface for listening to events and stopping them will be the same. This adds an advantage of making use of observables frequently for development purposes.
The basic usage of Observable in Angular is to create an instance to define a subscriber function. Whenever a consumer wants to execute the function the subscribe() method is called. This function defines how to obtain messages and values to be published.
Consider the below example constituting geolocation updates whenever a subscriber subscribes.
Creating an observable
Making API integration to check values
Data is ready for cleanup for next subscription using the below command.
Now, use subscribe() function for getting continuous updates using the below code:
Set the time intervals for 5 seconds which the notifications will be stopped automatically through the help of API integration. Consider the below code for reference.
Types of Notifications and Description
In this article, we learned the Observables from scratch and saw through an example how a subscribe() and unsubscribe() method works in a real-life geo-location application. We also came across various methods constituting the API integration techniques through which the time interval can be defined. Moreover, we came across various types of notifications along with their description which is specifically used whenever the subscriber subscribes or unsubscribes with the help of Observable.