Level Up Your Observables: RxJS Creation Functions Made Easy (Step-by-Step)
RxJS offers various creation functions to build and manage observable sequences. Here’s an explanation of some popular ones:
1. of()
: Emits a sequence of specified values synchronously.
Example:
TypeScript
const observable = of(1, 2, 3);
observable.subscribe(value => console.log(value)); // Output: 1, 2, 3
2. from()
: Converts various data sources into observables:
- Arrays:
from([1, 2, 3])
- Promises:
from(new Promise(resolve => resolve(10)))
- Iterables:
from([1, 2, 3].values())
- Events:
fromEvent(document, 'click')
3. interval()
: Emits a sequence of numbers periodically with a specified time interval.
Example:
TypeScript
const observable = interval(1000); // Emit every second
observable.subscribe(value => console.log(value)); // Output: 0, 1, 2, ...
4. timer()
: Emits a single value after a specified delay.
Example:
TypeScript
const observable = timer(2000); // Emit after 2 seconds
observable.subscribe(value => console.log(value)); // Output: 0 (after 2s)
5. range()
: Emits a sequence of numbers within a specified range.
Example:
TypeScript
const observable = range(1, 5); // Emit 1 to 5
observable.subscribe(value => console.log(value)); // Output: 1, 2, 3, 4, 5
6. throwError()
: Emits a specific error as an observable.
Example:
TypeScript
const observable = throwError(new Error('This is an error!'));
observable.subscribe(
value => console.log(value),
error => console.error(error.message) // Output: "This is an error!"
);
7. empty()
: Emits no values and completes immediately.
Example:
TypeScript
const observable = empty();
observable.subscribe(() => console.log('Completed')); // Output: "Completed"
8. defer()
: Creates an observable by calling a factory function each time someone subscribes. Useful for creating observables with dynamic data.
Example:
TypeScript
const observable = defer(() => timer(1000)); // Emit after 1s each subscription
observable.subscribe(value => console.log(value)); // Output: 0 (after 1s)
observable.subscribe(value => console.log(value)); // Output: 0 (after 1s again)
9. create()
: Offers low-level control over observable creation using a subscription function.
Example:
TypeScript
const observable = create(observer => {
observer.next(1);
observer.next(2);
observer.complete();
});
observable.subscribe(value => console.log(value)); // Output: 1, 2
10. fromevent(target, eventName): Converts DOM events into an observable sequence.
Example:
TypeScript
const button = document.getElementById('myButton');
const clicks = fromEvent(button, 'click');
clicks.subscribe(() => console.log('Button clicked!'));
This emits a value whenever the button with the ID myButton
is clicked.
11. forkJoin(...observables)
: Waits for all provided observables to complete and emits an array containing their last emitted values.
Example:
TypeScript
const userObservable = getUserDetails();
const postObservable = getPostData();
forkJoin(userObservable, postObservable).subscribe(([user, post]) => {
console.log(`User: ${user.name}, Post: ${post.title}`);
});
This waits for both getUserDetails
and getPostData
to finish, then emits an array containing their last emitted values (user object and post object).
12. combineLatest(...observables, project)
: Emits a value whenever any of the provided observables emits a value, combining them using a function.
Example:
TypeScript
const temperatureObservable = interval(1000).map(t => Math.random() * 20);
const humidityObservable = interval(2000).map(t => Math.random() * 100);
combineLatest(temperatureObservable, humidityObservable, (temp, humidity) => ({
temp: temp.toFixed(1),
humidity: humidity.toFixed(1)
})).subscribe(data => console.log(`Temp: ${data.temp}, Humidity: ${data.humidity}`));
This combines the latest values from both observables into an object, emitting it whenever either emits a new value.
These are just a few of the many creation functions available in RxJS. Choose the appropriate one based on your specific needs and data sources. Remember to explore the official documentation for more details and advanced operators. RxJS Documentation