Rxjs Basics
RxJS is a popular library for reactive programming in JavaScript. It provides a wide range of operators and utilities for working with streams of data, allowing developers to easily manipulate and transform data in real time.
Here are some basic examples of how to use RxJS to create and manipulate streams of data:
Creating observables
To create an observable in RxJS, you can use the Observable.create function, which takes a function as an argument. This function is called whenever the observable is subscribed to, and it is used to emit a stream of events. Here is an example:
const observable = Rx.Observable.create(function (observer) {
observer.next(1);
observer.next(2);
observer.next(3);
});
observable.subscribe(function (x) {
console.log(x);
});
In this code, the observable object emits three numbers: 1, 2, and 3. These numbers are then subscribed to by the subscribe function, which logs each number to the console as it is emitted.
Transforming observables
RxJS provides a wide range of operators that can be used to transform observables. For example, the map operator can be used to transform the items emitted by an observable by applying a function to each item. Here is an example:
const observable = Rx.Observable.create(function (observer) {
observer.next(1);
observer.next(2);
observer.next(3);
});
observable
.map(x => x * 10)
.subscribe(function (x) {
console.log(x);
});
In this code, the map operator is applied to the observable object, and the resulting stream of numbers is then subscribed to by the subscribe function. This time, each number is multiplied by 10 before it is logged to the console, so the output will be 10, 20, and 30 instead of 1, 2, and 3.
Combining observables
RxJS also provides operators for combining observables. For example, the merge operator can be used to merge the items emitted by two observables into a single observable. Here is an example:
const observable1 = Rx.Observable.create(function (observer) {
observer.next(1);
observer.next(2);
observer.next(3);
});
const observable2 = Rx.Observable.create(function (observer) {
observer.next(4);
observer.next(5);
observer.next(6);
});
Rx.Observable.merge(observable1, observable2).subscribe(function (x) {
console.log(x);
});
In this code, the merge operator is used to combine the items emitted by observable1 and observable2 into a single observable. The resulting observable is then subscribed to by the subscribe function, which logs each item to the console.