What is the Concept of Angular Observable?
Do you want to use Angular but are confused by the terminology? Have you heard of observables and want to know what they mean? Are you an Angular developer but do not yet understand the topic? Look no further, as this tutorial will help you to understand this core Angular concept. We will focus on understanding what Observables are, what they are for, and how they work in Angular.
What is observable?
An observable represents a set of values that the user can observe. You can use observable types of model push-based data sources such as DOM events, timer intervals, and sockets. The Observable constructor initializes a new Observable object. To create an observable instance, implement the observable in a function and pass that function to the observable constructor. The TC39 proposal calls this function the subscriber function. The subscribe function gets called whenever you subscribe to an observable instance.
Why use observables?
Let us now check out the reasons to use observables in the coding.
Generate data and send it to observers.
Applications contain code that produces data (producers), and code consumes data (consumers). Functions, promises, iterables, and observables are data producers in JavaScript. This is why the TC39 proposal said that you can model data sources using observable types. “Push-based” means you can control when an observable sends data to an observer. Manufacturers differ in how they interact with consumers. It can have a push or pull system, generate a single value or a series of values, and send data synchronously or asynchronously, lazily or eagerly.
Allow observers to subscribe
Creating an observable instance is not enough to start generating and sending data. You also need to subscribe to observables. Observables need to know where to send data. Observers tell observables that they are interested in receiving data by subscribing to it.
How do Observables work in Angular?
Observable behavior follows the Observer programming pattern. Observers have two main actors:
Observable
Observables fire data in response to events. For example, when a user clicks a button or responds to data received from a remote server.
Observer
An observer has three handles to use the received data. The developer uses onNext handles requested data, onError handles errors, and onComplete when the process ends.
Final Takeaway
The tutorial covers the basics of understanding Observables, using them, and working with Angular. It is the first chapter of the subject observables and will form the basis of further study. I will cover more about it in future blogs.