Implement a Tiny Observable From Scratch in JavaScript
Build a tiny observable from scratch in JavaScript with subscribe, teardown, map and filter operators, completion and error handling, plus tests. Node.js 24.

An observable is a function wearing a costume. Strip away the library and what remains is a value that describes how to produce a stream of values, and does nothing until someone subscribes. That single idea, laziness plus a way to stop, is what interviewers want to hear, and it takes about thirty lines to demonstrate. This post builds a tiny observable on Node.js 24: the core, the teardown that makes subscriptions cancellable, the map and filter operators and the rules for completion and errors. It does not try to replace RxJS. It shows what RxJS is made of, so the next time you read its source it is familiar. For the push-based cousin in the standard library, see building a pub/sub bus.
The contract
An observable is created from a function, usually called the subscriber function, that receives an observer. The observer has three methods: next(value) to emit, error(err) to fail and complete() to finish. The subscriber function may return a teardown function that releases resources. subscribe(observer) runs the subscriber function and returns a subscription with an unsubscribe method.
Three rules keep it honest. Nothing runs until subscribe. After error or complete, nothing more is delivered. And unsubscribe runs the teardown exactly once.
The core
class Observable {
constructor(subscriber) {
this._subscriber = subscriber;
}
subscribe(observerOrNext) {
const observer =
typeof observerOrNext === "function"
? { next: observerOrNext }
: (observerOrNext ?? {});
let closed = false;
let teardown;
const safe = {
next(value) {
if (!closed) observer.next?.(value);
},
error(err) {
if (closed) return;
closed = true;
try {
observer.error?.(err);
} finally {
teardown?.();
}
},
complete() {
if (closed) return;
closed = true;
try {
observer.complete?.();
} finally {
teardown?.();
}
},
};
teardown = this._subscriber(safe);
if (closed) {
teardown?.();
}
return {
unsubscribe() {
if (closed) return;
closed = true;
teardown?.();
},
};
}
}
const numbers = new Observable((observer) => {
observer.next(1);
observer.next(2);
observer.complete();
observer.next(3);
});
numbers.subscribe({
next: (v) => console.log("value", v),
complete: () => console.log("done"),
});value 1
value 2
doneThe 3 is never delivered, because complete() set closed. That guard in safe is the "no emissions after completion" rule, and it lives in one place so that no subscriber function can break it. Notice also that subscribe accepts a bare function as a shorthand for { next }, which is how most code calls it.
There is one awkward detail. A synchronous subscriber function that completes before it returns has not yet assigned teardown, so safe.complete() runs with teardown still undefined. The line if (closed) teardown?.() after the call handles that case, running the teardown late and once. Without it, a synchronous observable would leak whatever its teardown was meant to release.
Laziness
Nothing happens without a subscription, and each subscription runs the function again.
let runs = 0;
const cold = new Observable((observer) => {
runs += 1;
observer.next(runs);
observer.complete();
});
console.log(runs);
cold.subscribe((v) => console.log("first", v));
cold.subscribe((v) => console.log("second", v));
console.log(runs);0
first 1
second 2
2Creating the observable ran nothing. Each subscribe started its own execution, which is what RxJS calls a cold observable. A Promise differs on both counts: it starts working when created and runs once, however many callers read the result.
Teardown and unsubscribe
The subscriber function returns a cleanup function, which is the whole reason observables exist instead of plain callbacks. A timer is the classic case.
function interval(ms) {
return new Observable((observer) => {
let n = 0;
const id = setInterval(() => observer.next(n++), ms);
return () => {
clearInterval(id);
console.log("cleaned up");
};
});
}
const seen = [];
const subscription = interval(5).subscribe((n) => {
seen.push(n);
if (n === 2) {
subscription.unsubscribe();
}
});
await new Promise((resolve) => setTimeout(resolve, 50));
console.log(seen);cleaned up
[ 0, 1, 2 ]After the third value, the callback unsubscribes. The teardown clears the interval, so the process is not kept alive and no fourth value arrives. A caveat worth knowing: here subscription is read inside the callback, which only runs after subscribe has returned because the first tick comes from a timer. A synchronous source would call the callback before the assignment finished, and the usual fix is to give observers access to a closed flag, as the real libraries do.
Operators are functions that return observables
An operator takes a source observable and returns a new one. The new one subscribes to the source when it is subscribed to, and passes its own unsubscribe through. map is the shortest example.
const map = (fn) => (source) =>
new Observable((observer) => {
const subscription = source.subscribe({
next: (value) => observer.next(fn(value)),
error: (err) => observer.error(err),
complete: () => observer.complete(),
});
return () => subscription.unsubscribe();
});
const filter = (predicate) => (source) =>
new Observable((observer) => {
const subscription = source.subscribe({
next: (value) => {
if (predicate(value)) observer.next(value);
},
error: (err) => observer.error(err),
complete: () => observer.complete(),
});
return () => subscription.unsubscribe();
});
Observable.prototype.pipe = function (...operators) {
return operators.reduce((source, operator) => operator(source), this);
};
const from = (items) =>
new Observable((observer) => {
for (const item of items) observer.next(item);
observer.complete();
});
from([1, 2, 3, 4, 5, 6])
.pipe(
filter((n) => n % 2 === 0),
map((n) => n * 10),
)
.subscribe({
next: (v) => console.log(v),
complete: () => console.log("done"),
});20
40
60
doneEvery operator has the same shape, a function from observable to observable, which is why pipe is a plain reduce. The returned teardown matters: unsubscribing from the result unsubscribes from the source, all the way back to the timer or socket at the start of the chain. If an operator forgot to return it, a subscription would appear cancelled while the source kept running, which is a classic leak.
Errors
An error terminates the stream, like completion, and an exception thrown by a mapping function should become an error notification and not escape.
const safeMap = (fn) => (source) =>
new Observable((observer) => {
const subscription = source.subscribe({
next: (value) => {
try {
observer.next(fn(value));
} catch (err) {
observer.error(err);
}
},
error: (err) => observer.error(err),
complete: () => observer.complete(),
});
return () => subscription.unsubscribe();
});
from([1, 2, 3])
.pipe(
safeMap((n) => {
if (n === 2) throw new Error("bad value");
return n;
}),
)
.subscribe({
next: (v) => console.log("value", v),
error: (e) => console.log("error", e.message),
complete: () => console.log("done"),
});value 1
error bad valueThe 3 and done never appear, because the error closed the stream. With plain map the exception would have propagated out of observer.next into the source's loop, and in a real library that is the difference between a handled failure and an uncaught exception. Note that a try around observer.next in the version above would also catch an error thrown by the downstream observer itself, so a production library separates the two. For a tiny version, say so and move on.
Observable versus the alternatives
| Promise | Async iterator | Observable | |
|---|---|---|---|
| Values | one | many, pulled by the consumer | many, pushed by the producer |
| Starts | on creation | on first next() call | on subscribe |
| Cancel | not built in | return() | unsubscribe |
| Backpressure | not applicable | built in, consumer paces | none, the producer decides |
The last row is the honest limit of the tiny version. A fast producer can flood a slow observer, because next is a plain call. Async iterators avoid that because the consumer asks for each value. An EventTarget or a DOM event is also a push source, and wrapping one in an observable is a good exercise: addEventListener in the subscriber function, removeEventListener as the teardown.
Wrapping an event source
The best way to feel why teardown exists is to turn a DOM-style event source into an observable. Any EventTarget has addEventListener and removeEventListener, and the two map directly onto the subscriber function and its teardown. The subscriber registers a listener that forwards each event to observer.next, and the teardown removes that same listener.
Node.js has an EventTarget global, so this works without a browser. Two points matter in practice. The listener function must be the same reference in both calls, which is why it is declared as a variable and not written inline twice, since removeEventListener compares by reference. And an event source never completes by itself, so the stream ends only when the subscriber unsubscribes, which is exactly the case where forgetting the teardown leaves a listener attached for the life of the page.
Once you can wrap one source, the same pattern covers timers, sockets and file watchers. Each is a few lines: acquire in the subscriber function, release in the returned function. That repetition is the argument for the abstraction. Without it, every call site has to remember its own cleanup, and the one that forgets is the one that leaks.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("emits, then completes, then stops", () => {
const log = [];
from([1, 2]).subscribe({
next: (v) => log.push(v),
complete: () => log.push("done"),
});
assert.deepEqual(log, [1, 2, "done"]);
});
test("teardown runs once on unsubscribe", () => {
let cleanups = 0;
const source = new Observable(() => () => (cleanups += 1));
const subscription = source.subscribe(() => {});
subscription.unsubscribe();
subscription.unsubscribe();
assert.equal(cleanups, 1);
});
test("operators compose", () => {
const out = [];
from([1, 2, 3]).pipe(map((n) => n + 1)).subscribe((v) => out.push(v));
assert.deepEqual(out, [2, 3, 4]);
});ℹ tests 3
ℹ pass 3
ℹ fail 0Where this stops
The tiny version has no schedulers, no multicasting and no backpressure, and it shares one weakness with every hand-written observable: error handling inside observers is easy to get subtly wrong. If you need these in production, use a library that has been through those edge cases. There is also an Observable proposal for the platform, and EventTarget-based APIs in browsers may cover simple cases without any library, so check what your runtime provides before adding a dependency.


