53. Creating and Subscribing to Observables
There are several factory functions in RxJS used to easily create Observables.
1. Creating Observables from Scratch
Use new Observable() when bridging asynchronous sources (like setInterval or WebSockets) that don't natively return Observables.
typescript import { Observable } from 'rxjs';
const mouseMove$ = new Observable
// Return the teardown function for cleanup return () => document.removeEventListener('mousemove', handler); });
const subscription = mouseMove$.subscribe(event => {
console.log(Mouse at: ${event.clientX}, ${event.clientY});
});
// To stop listening: // subscription.unsubscribe();
2. Factory Functions for Simple Sources
| Factory | Description |
|---|---|
of() | Emits a fixed sequence of values and then completes. |
from() | Converts an array, promise, or iterable into an Observable. |
interval() | Emits sequential numbers periodically. |
timer() | Emits one value after a specified delay, then optionally repeats. |
typescript import { of, from } from 'rxjs';
of(10, 20, 30).subscribe(val => console.log('of:', val)); // Emits 10, 20, 30, then completes
from(['A', 'B', 'C']).subscribe(val => console.log('from:', val)); // Emits A, B, C, then completes
// interval(1000).subscribe(count => console.log(count)); // Emits 0, 1, 2, ... every second (never completes)
3. The Subscription Object
When we call subscribe(), we get a Subscription object. Always keep track of subscriptions for long-lived Observables and call unsubscribe() in ngOnDestroy.