🌊 RxJS & Observables
Reactive programming with streams, operators, and automatic cleanup
About This Feature
RxJS is Angular's reactive programming library. It lets you treat events and async data as streams you can compose with operators.
Observable— lazy stream of values over timeSubject— multicast observable + observer; manually push valuesBehaviorSubject— Subject with an initial value; replays last value to new subscribersdebounceTime— wait for a pause before emitting (e.g., search)distinctUntilChanged— skip duplicate consecutive valuesscan— accumulate values over time (like Array.reduce)takeUntil— complete when another observable emits (memory-safe unsubscribe)
Code Example
// Subject — multicast observable, no initial value
private search$ = new Subject<string>();
// BehaviorSubject — has initial value, emits to late subscribers
private events$ = new BehaviorSubject<string[]>([]);
// Operators pipeline
this.search$.pipe(
debounceTime(400), // wait 400ms after last emission
distinctUntilChanged(), // ignore duplicate values
map(term => term.toLowerCase()),
filter(term => term.length > 0),
takeUntil(this.destroy$) // auto-unsubscribe on destroy
).subscribe(term => { /* handle */ });
// interval + takeUntil
private stop$ = new Subject<void>();
interval(1000)
.pipe(takeUntil(this.stop$))
.subscribe(n => this.tick = n);
// scan() — accumulates values like Array.reduce
clicks$ = clickSubject$.pipe(
scan((total) => total + 1, 0),
startWith(0)
);
// Cleanup in ngOnDestroy
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}Live Demo
Subject + debounceTime + distinctUntilChanged
Type to search…
BehaviorSubject (event bus)
Click a button to emit events…
interval() + takeUntil() (auto-cleanup)
0s
scan() — accumulates clicks
Total via
scan(): 0