RxJS Fundamentals
1. Introduction
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables, which makes it easier to compose asynchronous or callback-based code. In the Angular ecosystem, RxJS is widely used for handling asynchronous data flows.
2. Core Concepts
2.1 Observables
Observables are the foundational building blocks of RxJS. They represent a stream of data that can be observed and manipulated.
2.2 Subscribers
A subscriber is a consumer of the Observable data. It listens to the Observable and acts on the emitted values.
const observable = new Observable(subscriber => {
subscriber.next('Hello RxJS!');
subscriber.complete();
});
observable.subscribe(value => console.log(value));
2.3 Operators
Operators are functions that enable you to transform, filter, or combine Observables. They can be categorized into:
- Creation Operators
- Transformation Operators
- Filtering Operators
- Combination Operators
3. Operators
Operators can be used to perform various operations on Observables. Here are some common operators:
- map: Transforms each emitted value.
import { map } from 'rxjs/operators';
observable.pipe(map(value => value.toUpperCase()));
import { filter } from 'rxjs/operators';
observable.pipe(filter(value => value.length > 5));
4. Subjects
Subjects are special types of Observables that allow values to be multicasted to many Observers. They can act as both an Observable and an Observer.
import { Subject } from 'rxjs';
const subject = new Subject();
subject.subscribe(value => console.log('Subscriber 1: ' + value));
subject.next('Hello World!');
5. Best Practices
- Use the async pipe in templates to handle subscriptions automatically.
- Unsubscribe from Observables to prevent memory leaks.
- Use operators to compose complex data flows cleanly.
6. FAQ
What is the difference between Observable and Promise?
Observables can emit multiple values over time, whereas a Promise can only resolve once.
How do I unsubscribe from an Observable?
You can unsubscribe by calling the unsubscribe()
method on the subscription object.