Sunday 4 June 2023

What do you understand by observable and observer in Angular?Example

In Angular, observables and observers play a crucial role in enabling reactive programming and managing data flow within applications. These concepts form the foundation of the RxJS library, widely used in Angular for handling asynchronous operations. In this article, we will explore the concepts of observables and observers in Angular and demonstrate their usage with a practical example.

1. Understanding Observables: 

Observables in Angular represent streams of data that can emit values over time. They can emit various types of data, such as numbers, strings, or custom objects, either synchronously or asynchronously. Observables provide a way to handle and react to changes or events in an application.

To create an observable in Angular, we can utilize the Observable class from the RxJS library. Let's consider an example of a simple observable that emits a sequence of numbers:

typescript
import { Observable } from 'rxjs'; const numberObservable = new Observable((observer) => { observer.next(1); observer.next(2); observer.next(3); observer.complete(); });

In the above example, we create an observable called numberObservable. Within the observable's constructor function, we use the observer parameter to emit values using the next() method. Finally, we call the complete() method to indicate the completion of the observable.

2. Understanding Observers: 

Observers in Angular are entities that subscribe to observables and receive the emitted values. An observer is an object that defines three optional callback functions: next(), error(), and complete(). These functions handle the emitted values, potential errors, and the completion event of the observable, respectively.

To create an observer, we can define an object with the desired callback functions. Let's create an observer for our numberObservable example:

typescript
const numberObserver = { next: (value) => console.log(value), error: (error) => console.error(error), complete: () => console.log('Observable completed'), };

In the above example, we define an observer called numberObserver. It specifies the next(), error(), and complete() functions to handle the emitted values, errors, and completion event of the observable, respectively.

Subscribing to Observables: To establish the connection between an observable and an observer, we use the subscribe() method. The subscribe() method allows an observer to listen to an observable and receive the emitted values. 

Let's subscribe to our numberObservable with the numberObserver:

typescript
numberObservable.subscribe(numberObserver);

In the above example, we subscribe to the numberObservable using the subscribe() method and provide the numberObserver as an argument. This establishes the connection between the observable and the observer.

Example Usage and Output: Let's consider a practical example to better understand the interaction between observables and observers in Angular. Suppose we have an observable that simulates fetching data from an API and emits the response. We can create an observable and an observer to handle the emitted data as follows:

typescript
import { Observable } from 'rxjs'; const dataObservable = new Observable((observer) => { setTimeout(() => { observer.next('Data received'); observer.complete(); }, 2000); }); const dataObserver = { next: (data) => console.log('Received data:', data), complete: () => console.log('Observable completed'), }; dataObservable.subscribe(dataObserver);

In the above example, we create an observable dataObservable that uses a setTimeout function to simulate data fetching. After a 2-second delay, the observable emits the string 'Data received' using the next() method and completes using the complete() method. The dataObserver handles the emitted data and completion event.


output
Received data: Data received Observable completed

Conclusion: Observables and observers are fundamental concepts in Angular that enable reactive programming and efficient data flow management. Observables represent streams of data that emit values over time, while observers subscribe to these observables to receive and handle the emitted values. By utilizing observables and observers effectively, developers can build robust and reactive Angular applications.

Also, read: 

No comments:

Post a Comment

Seven front-end development trends in 2023-2024

With the increasing prevalence of apps in the digital landscape , the role of front-end developers remains essential. While apps aim to ove...

Popular Posts