HOWTO · JavaScript
JavaScript Subscription Method
How to create and execute the subscription using subscribe() method in our JavaScript code statements with different examples.
On this page
We will learn how RxJS subscribe() starts an Observable execution, how to handle its notifications, and how unsubscribe() stops work and releases resources. A jQuery event plugin may also use the name subscribe(), but that is a separate API with different behavior.
Subscribe to an RxJS Observable
An Observable describes how values can be produced. Calling subscribe() starts an execution for that subscriber and returns a Subscription object. The object represents that particular execution and gives you a way to stop it. Calling subscribe() again creates a separate subscription; it does not merely attach another callback to a shared Promise.
In RxJS, a common source is interval(1000), which emits an increasing number once per second. For example, const subscription = interval(1000).subscribe(value => console.log(value)); starts that work. The following dependency-free teaching model shows the notification and teardown lifecycle; it is not the RxJS implementation. Its teardown runs once after normal completion, after an error, or when an active subscription is explicitly unsubscribed.
Run this example:
function observable(produce) {
return {
subscribe(observer) {
let closed = false;
let teardown;
let teardownRequested = false;
let teardownRan = false;
function runTeardown() {
if (teardownRequested && teardown && !teardownRan) {
teardownRan = true;
teardown();
}
}
function close() {
if (!closed) {
closed = true;
teardownRequested = true;
runTeardown();
}
}
const safeObserver = {
next(value) {
if (!closed) observer.next(value);
},
error(error) {
if (!closed) {
close();
if (observer.error) observer.error(error);
}
},
complete() {
if (!closed) {
close();
if (observer.complete) observer.complete();
}
}
};
teardown = produce(safeObserver);
runTeardown();
return { unsubscribe: close };
}
};
}
const source = observable(observer => {
observer.next("first");
observer.next("second");
observer.complete();
return () => console.log("cleanup");
});
source.subscribe({
next: value => console.log("value:", value),
error: error => console.log("error:", error.message),
complete: () => console.log("complete")
});
let errorCleanupCount = 0;
observable(observer => {
observer.error(new Error("source failed"));
return () => { errorCleanupCount += 1; };
}).subscribe({ error: () => {} });
if (errorCleanupCount !== 1) throw new Error("error teardown did not run once");
let cancelCleanupCount = 0;
const active = observable(() => () => { cancelCleanupCount += 1; }).subscribe({});
active.unsubscribe();
active.unsubscribe();
if (cancelCleanupCount !== 1) throw new Error("unsubscribe teardown did not run once");
value: first
value: second
complete
cleanup
The output shows the normal completion path. The additional checks exercise error and explicit unsubscription, confirming that each path invokes teardown once; repeated unsubscription is harmless. In RxJS, the library’s Subscription performs that resource-management role; use RxJS Observables and Subscriptions in application code.
Handle Observable Notifications
An observer can provide three callbacks: next for each value, error for a failure, and complete when the source finishes normally. These are distinct notifications, not Promise methods. An error ends that execution, and completion is sent only when the source completes; neither callback means “run in any case.” A source that never completes can continue sending values until it is unsubscribed.
For RxJS, pass an observer object such as { next: value => handle(value), error: error => report(error), complete: () => finish() } to subscribe(). Provide an error handler when the application needs to respond to a source failure. Keep the callback work focused, and remember that values may arrive more than once.
Unsubscribe and Group Subscriptions
Call subscription.unsubscribe() when the work is no longer needed. Unsubscribing stops that subscription’s notifications and runs teardown registered by the source. It does not reverse work already completed, and it does not necessarily stop a source shared with other active subscribers.
For example, start const timer = interval(1000).subscribe(value => console.log(value));, then call timer.unsubscribe() when the timer is no longer needed. A Subscription can also own child subscriptions: create a parent with new Subscription(), add each child using parent.add(child), and call parent.unsubscribe() to clean up the group. The parent-child relationship matters: adding a child after the parent has already been unsubscribed causes that child to be unsubscribed as well. Keep the parent variable consistent when adding and later cancelling the group.
Use the jQuery subscribe() Plugin
Some jQuery event-aggregation plugins expose a subscribe(topic, handler) function. In that API, the topic is an event name and the handler receives the event’s data; it is not RxJS’s Observable subscription. The source material does not identify the plugin or its package, so its exact call signature, setup, and cleanup method cannot be verified here.
Treat a call such as subscribe("HelloWorld", handler) as conceptual until you confirm the plugin’s documentation. Check how that particular plugin publishes a topic and removes a handler before using it. Do not mix its event names or cleanup rules with RxJS’s Subscription object.