Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change (Wikipedia). RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code (RxJS Docs).
RxJS provides an implementation of the Observable type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:
- Converting existing code for async operations into observables
- Iterating through the values in a stream
- Mapping values to different types
- Filtering streams
- Composing multiple streams
Observable creation functions
RxJS offers a number of functions that can be used to create new observables. These functions can simplify the process of creating observables from things such as events, timers, promises, and so on. For example:
Create an observable from a promise
import { fromPromise } from ‘rxjs’;
// Create an Observable out of a promise
const data = fromPromise(fetch(‘/api/endpoint’));
// Subscribe to begin listening for async result
data.subscribe({
next(response) { console.log(response); },
error(err) { console.error(‘Error: ‘ + err); },
complete() { console.log(‘Completed’); }
});
Create an observable from a counter
import { interval } from ‘rxjs’;
// Create an Observable that will publish a value on an interval
const secondsCounter = interval(1000);
// Subscribe to begin publishing values
secondsCounter.subscribe(n =>
console.log(`It’s been ${n} seconds since subscribing!`));
Create an observable from an event
import { fromEvent } from ‘rxjs’;
const el = document.getElementById(‘my-element’);
// Create an Observable that will publish mouse movements
const mouseMoves = fromEvent(el, ‘mousemove’);
// Subscribe to start listening for mouse-move events
const subscription = mouseMoves.subscribe((evt: MouseEvent) => {
// Log coords of mouse movements
console.log(`Coords: ${evt.clientX} X ${evt.clientY}`);
// When the mouse is over the upper-left of the screen,
// unsubscribe to stop listening for mouse movements
if (evt.clientX < 40 && evt.clientY < 40) {
subscription.unsubscribe();
}
});
Create an observable that creates an AJAX request
import { ajax } from ‘rxjs/ajax’;
// Create an Observable that will create an AJAX request
const apiData = ajax(‘/api/data’);
// Subscribe to create the request
apiData.subscribe(res => console.log(res.status, res.response));