Do you want a different way to handle state in your Javascript applications? Then I suggest giving Reactive Programming a try, and more specifically, RxJS. RxJS is a framework-agnostic library that provides tools for applying the Observer pattern. RxJS has extensive operators for handling state, and it is equipped with asynchronous event management functions. This means that no additional libraries are required to handle the asynchronous events for your application, which leads to a leaner dependency tree.
What is an observable in RxJS?#
An Observable in RxJS is a lazy push collection of multiple values, says the RxJS Observable guide. It can return zero to (potentially) infinite values, synchronously or asynchronously, from the time it is invoked. A function returns a single value when you call it. A Promise may or may not return a single value, some time later. An Observable fits a value that keeps changing, such as a live feed, while a Promise fits one answer that arrives once.
Lazy means the code inside an Observable does not run until something subscribes to it. Two subscribes run it twice, as two separate side effects. An event emitter works the other way: it shares its side effects and runs eagerly, whether or not anything subscribes.
Push is about who controls the timing. In a pull system, the consumer decides when it receives data, and the producer only produces data when asked. Calling a function is pull: your code asks, and the function returns one value. An iterator is pull with many values: each call to iterator.next() pulls out the next one. In a push system, the producer decides when to send data and works at its own pace. The consumer just reacts to what it receives. A Promise is push: the Promise decides when its value reaches the callbacks.
The RxJS docs put these four types on one grid. The Observable fills the spot for push with multiple values.
| System | Single value | Multiple values |
|---|---|---|
| Pull | Function | Iterator |
| Push | Promise | Observable |
You can create an Observable yourself with new Observable. Most often, though, you use a creation function, one that builds the Observable for you, such as of, from or interval.
What is the Observer Pattern?#
The Observer pattern is a sequence of the following events:
1. New data is emitted or state has changed in an Observable object.
2. The Observers of the Observable are notified of the change.
Subscribing to events#
In RxJS all Observables have an internal subscribe function, this function is how different Observers throughout the application are notified of Observables updates.
What does an Observer receive: next, error and complete?#
An Observer is a set of callbacks, one for each type of notification an Observable delivers: next, error and complete, as the RxJS Observer guide puts it. An Observable can send any number of next notifications. After them it may send one error or one complete, never both, and nothing after either one.
Next carries a value. Error carries a JavaScript Error or exception. Complete carries no value. The Observable guide writes the whole rule as next*(error|complete)?.
Observers may be partial. A missing next or complete callback just means that type of notification is ignored. If you pass a single function to subscribe, RxJS uses it as the next callback.
Here is a client list with a full Observer, in one file:
import { of } from 'rxjs';
const clientList = ['clientOne', 'clientTwo', 'clientThree'];
of(...clientList).subscribe({
next: (client) => console.log('next:', client),
error: (err) => console.log('error:', err),
complete: () => console.log('the end'),
});It prints:
next: clientOne
next: clientTwo
next: clientThree
the endWith of, each argument becomes one next notification. Nothing goes wrong here, so the error callback does not run. The npm package name is lowercase: install it with npm install rxjs and import from 'rxjs', as the RxJS docs do. The npm registry has no package named RxJS.
How do you unsubscribe from an observable?#
Calling subscribe returns a Subscription, an object that represents a disposable resource, usually the execution of an Observable, says the RxJS Subscription guide. Call its unsubscribe() method to cancel that execution and dispose of the resources it holds. An Observable that completes on its own, like one made with of, delivers nothing after its complete notification.
The docs show it with interval(1000), which emits a number every second:
import { interval } from 'rxjs';
const subscription = interval(1000).subscribe((x) => console.log(x));
// Later:
subscription.unsubscribe();The unsubscribe() call cancels the ongoing execution, and no more numbers arrive.
Subscriptions can be grouped. subscription.add(childSubscription) puts one inside another, so a single unsubscribe() call unsubscribes both. remove(childSubscription) undoes the addition.
When you create an Observable yourself with new Observable, you dispose of its resources by returning a custom unsubscribe function from it. In the docs' example, that function calls clearInterval to stop a timer:
import { Observable } from 'rxjs';
const observable = new Observable(function subscribe(subscriber) {
// Keep track of the interval resource
const intervalId = setInterval(() => {
subscriber.next('hi');
}, 1000);
// Provide a way of canceling and disposing the interval resource
return function unsubscribe() {
clearInterval(intervalId);
};
});Here subscriber.next('hi') sends a value every second. With new Observable, your own code decides when each value goes out. With of, RxJS sends one value per argument for you. The guide says the function you return is conceptually equal to subscription.unsubscribe. The Observable, Observer and Subscription types add safety, such as the Observable contract (the next, error and complete rule above), and let you compose them with operators.
If an Observable may keep sending values, as interval does, unsubscribe once you no longer need them.
Potential Snags#
Here are some considerations before using this library.
RxJS requires time to learn, implement, and practice. Engineers, make sure that there is ample runway to get everyone in your team up to speed because the learning curve can get steep quickly.
The documentation is dense, it will most likely require more than one read through to grasp the concepts required to use it. We would like to see the RxJS authors polish its wording to make it more user friendly.
Below is a simple example to get started with Observables using RxJS.
How to Create an RxJS Observable#
Install RxJS in your project:
npm install RxJSIn our main.js file:
import { of } from '`RxJS`'
import './subscriptions'
const clientList = ['clientOne', 'clientTwo', 'clientThree']
export const clientsObs = of(...clientList)In our subscriptions.js file:
import { clientObs } from './main.js'
clientsObs.subscribe(client => `console.log`(client))The result of our console.log:
clientOne
clientTwo
clientThree1. In your main.js file import RxJS.
2. Create a list of clients.
3. Convert the list of clients into an Observable using the of function.
4. Import the clientObs variable to the subscription module, and connect to it using the subscribe method.
By using the subscribe function in our subscription file, you create an Observer of the clientObs. This Observer will be notified of new events emitted from the clientsObs, which is exported from the main.js file. In this example our events print to the console.log.
This pattern is useful because it allows us to write decoupled code, that is still aware of events and new data from other observed sources.
In our example we have defined an Observable from our clientList named clientsObs, we imported our clientObs to our subscription file, in our subscription file we subscribe to the clientObs, this action of subscribing makes the subscription file an Observer, then the clientObs emitted three different events at different times, and our subscription Observer printed those events to the console.
Congratulations, we have written our first Observable
Observable vs promise: what is the difference?#
A Promise returns a single value at most, and its executor, the function you pass to new Promise(), runs as soon as the Promise is constructed, per MDN's reference for Promise(). An Observable can return zero to many values over time, and its code runs only when you subscribe, per the RxJS Observable guide. You can cancel an Observable's execution with unsubscribe().
The three differences side by side:
| Question | Promise | Observable |
|---|---|---|
| How many values? | One, or none | Zero to many |
| When does its code run? | When it is constructed | When you subscribe |
| Can you cancel it? | No built-in way | Yes, with unsubscribe() |
Promise itself has no first-class protocol for cancellation, MDN notes. You may be able to cancel the work underneath it instead, typically using AbortController.
An Observable can deliver its values synchronously or asynchronously.
A simple way to choose: use a Promise, or async and await, when you need one future value. Use an Observable when values keep arriving, or when you need to stop listening.
You can also turn an Observable into a Promise. The older toPromise() method is deprecated, says the RxJS deprecation guide. Use firstValueFrom or lastValueFrom instead.
firstValueFromresolves with the first value, then unsubscribes right away.lastValueFromwaits for the Observable to complete, then resolves with the last value.- Both reject with an EmptyError if the Observable completes without sending a value, unless you pass a
defaultValuein the second parameter.
Only use lastValueFrom on an Observable you know will complete. Otherwise the Promise can be left hung up. Here is firstValueFrom in use:
import { interval, firstValueFrom } from 'rxjs';
async function execute() {
const numbers = interval(2000);
const firstNumber = await firstValueFrom(numbers);
console.log(`The first number is ${firstNumber}`);
}
execute();
// The first number is 0Going the other way, from turns a Promise into an Observable. Its API page says it converts almost anything to an Observable, including an Array, an iterable object or a Promise. Here it wraps a Promise of one client name:
import { from } from 'rxjs';
const clientPromise = Promise.resolve('clientOne');
from(clientPromise).subscribe({
next: (client) => console.log('next:', client),
complete: () => console.log('the end'),
});
// next: clientOne
// the endWhat is a Subject in RxJS?#
A Subject is an Observable that multicasts one execution to many Observers, says the RxJS Subject guide. It keeps a list of Observers and sends each value to all of them. Every Subject is also an Observer, so you push values into it with next(). Reach for a Subject when several parts of a page must see the same values at the same time; when each subscriber should get its own run, a plain Observable is simpler.
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe((v) => console.log(`observerA: ${v}`));
subject.subscribe((v) => console.log(`observerB: ${v}`));
subject.next(1);
// observerA: 1
// observerB: 1Both subscribers get the value 1 from a single next(1) call. The <number> part is a TypeScript type. Leave it out in plain JavaScript.
What are hot and cold observables?#
A cold Observable creates a new producer for each subscription, while a hot Observable uses a producer that was created outside the subscription, per the RxJS glossary. The producer is the source of the values, which can be anything from a WebSocket to a simple iteration over an Array. A cold Observable is always unicast, and a hot one is almost always multicast.
The of and interval examples on this page use plain Observables, so each subscribe starts its own run, which makes them cold. The Subject example above is different, because one next(1) call reached both subscribers.
Where are observables used?#
Two places you will meet Observables are browser events and Angular's HTTP client. For events, the RxJS overview replaces document.addEventListener with fromEvent, which creates an Observable of one event type from a target such as document. In Angular, each HttpClient method returns an RxJS Observable that sends the request when subscribed, the Angular HTTP guide says.
import { fromEvent } from 'rxjs';
fromEvent(document, 'click').subscribe(() => console.log('Clicked!'));Angular's HttpClient produces cold Observables. No request goes to the server until the Observable is subscribed, and each subscription makes a new backend request.
Do you need RxJS for a given job? A short rule of thumb:
- One future value: a Promise is enough.
- One browser event:
addEventListeneris enough. - Streams you need to map or filter: that is the job of RxJS operators, which are inspired by Array methods such as map, filter and reduce.
The infinite scroll example in React on this blog uses the Intersection Observer API and a custom hook, with no RxJS.
Whether RxJS belongs in a project is a stack decision. The Gnar evaluates your business goals, user needs, scalability requirements, and technical constraints to recommend the best technology stack.
Summary#
If you are considering using this library, just remember that RxJS has its snags in the form of time and dense documentation. On the other hand, RxJS allows us to write applications using the Observer Pattern, which is powerful and useful, because out of the box we can write different Observable sources anywhere in our project. RxJS works well with established libraries, plays nice with Typescript, and addresses scalability issues through it's many operators.
Give RxJS and Observables a try if you are interested in exploring another way to manage state in Javascript.
Learn more about how The Gnar builds React applications.


