Course contentsShow
← JavaScript
Lesson 1879 of 2,72339. Memory Management and GCFree lesson

Observables and Subscriptions

Managing RxJS or event stream subscriptions that hold references until explicitly unsubscribed.

Observables and Subscriptions

You'll learn how RxJS observables and event streams can cause memory leaks if subscriptions aren't properly cleaned up.

What Are Observables and Subscriptions?

Observables (from libraries like RxJS) represent streams of data over time—like events, HTTP responses, or timers. When you subscribe to an observable, you're saying "call this function whenever new data arrives." The subscription object keeps a reference to your callback, and the observable keeps a reference to the subscription. Until you explicitly unsubscribe, those references stay alive.

Think of it like subscribing to a magazine. The publisher keeps your address on file and sends you issues every month. Even if you move or lose interest, you'll keep getting magazines (and they'll keep piling up) until you call and cancel your subscription.

The Memory Leak Problem

// ❌ Memory leak: subscription never cleaned up
function startListening() {
  const dataStream$ = createObservable();
  
  dataStream$.subscribe(data => {
    console.log(data);
    // This callback stays in memory forever!
  });
}

// ✅ Properly cleaned up
function startListening() {
  const dataStream$ = createObservable();
  
  const subscription = dataStream$.subscribe(data => {
    console.log(data);
  });
  
  // Later, when done:
  subscription.unsubscribe();
}

If you create subscriptions in components that mount/unmount or functions that run repeatedly, each one adds another reference chain. Those callbacks, along with any variables they close over, remain in memory until unsubscribed.

Key Takeaway: Always store subscription objects and call .unsubscribe() when you're done listening—especially in component cleanup, route changes, or when stopping long-lived processes. Forgetting to unsubscribe is one of the most common observable-related memory leaks.