Middle
What is an observable?
sobes.tech AI
Answer from AI
Observable is an entity that represents a stream of data or events, which can be asynchronous. Observable sources can emit values over a period of time, and subscribers (Subscribers or Observers) can react to these values as they appear.
Key concepts:
- Observable (Observable source): A data or event source.
- Observer (Observer): An object with methods to react to events from the Observable (
next,error,complete).next: Receiving the next value.error: An error occurs.complete: The data stream is finished.
- Subscription: The connection between an Observable and an Observer. A subscription is created when the
subscribemethod is called on an Observable. It allows the Observer to receive values and manage the lifecycle of the subscription (e.g., unsubscribe to prevent memory leaks). - Operators: Functions for transforming, combining, and managing Observable streams. Examples include
map,filter,mergeMap,debounceTime.
Unlike Promises, Observables can emit multiple values over time, representing data streams rather than a single asynchronous event.
Example of usage in RxJS (a popular library for reactive programming):
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
// Creating an Observable from an array
const source = new Observable(observer => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete(); // Completing the stream
});
// Subscription and operator usage
const subscription = source.pipe(
map(value => value * 2) // The map operator doubles each value
).subscribe({
next: value => console.log(value), // Receiving values: 2, 4, 6
error: err => console.error(err), // Error handling
complete: () => console.log('Complete!') // Completion
});
Main advantages:
- Reactive programming: Convenient management of asynchronous data streams.
- Composability: Easy to combine and transform streams using operators.
- Lifecycle management: Subscription allows explicit control over data reception and prevents memory leaks.