| | |

RxJS 02 ๐ŸŸฃ Observables, Observers & Subscriptions โ€” Creating Observables, handling next/error/complete, and teardown logic

โฑ๏ธ Estimated read: 12 min | |

The power of RxJS lies in its formalization of how data is produced, consumed, and cleaned up. While many developers are familiar with the concept of “listening to events,” RxJS provides a strict structure for this interaction through the triad of Observables, Observers, and Subscriptions. These three pieces represent the lifecycle of any reactive operation, from its definition to its eventual termination.

An Observable is essentially a blueprint for a stream. It defines how data should be generated, but it remains dormant until it is actually put into use. The Observer is the set of instructions for what to do with that data once it arrives, acting as a “handler” for the three types of notifications: data, errors, and completion. The Subscription is the bridge between the two; it represents the active execution of the stream and provides the handle needed to stop it.

In this chapter, we will look at the mechanics of creating Observables from scratch using the constructor. We will explore the internal execution context of an Observable and how it interacts with the Observer’s interface. We will also focus heavily on resource management, specifically how to write teardown logic that prevents memory leaks when a stream is no longer needed.

By understanding these fundamentals, you move beyond simply using built-in creation functions like of or fromEvent. You gain the ability to wrap any custom logicโ€”whether itโ€™s a legacy callback, a WebSocket connection, or a complex intervalโ€”into a first-class Observable that behaves predictably within the RxJS ecosystem.

Key point: An Observable is a lazy collection of multiple values that are pushed to an Observer over time; the interaction only begins with a Subscription, which must eventually be unsubscribed to trigger the teardown logic defined inside the Observable.


Why exists

The “Lifecycle Standard” problem

Before RxJS, every asynchronous API had its own way of starting, stopping, and handling errors. setInterval uses an ID, XMLHttpRequest uses event listeners, and Promises use .then(). RxJS exists to provide a single, unified interface for all of these patterns. By using Observables, you can treat a click event exactly the same way you treat a database query or a timer.

The “Dormant Logic” problem

Often, we want to define how an event should be handled without actually starting the process immediately. Observables allow for this “lazy” definition. You can build complex pipelines of logic, and they will only consume CPU and memory resources at the moment someone actually subscribes to them. This makes code more modular and efficient.

The “Resource Leak” problem

Managing the cleanup of asynchronous operations is a common source of bugs. If you start a timer or open a socket, you must remember to close it. RxJS formalizes this through “Teardown Logic.” Every Observable can return a cleanup function that is automatically called when the consumer unsubscribes, ensuring that resources are always released.

The “Terminal State” problem

Promises only have two states: resolved or rejected. They don’t have a concept of “I’m done sending multiple values.” Observables introduce the complete notification. This allows a producer to signal that it has finished its work successfully, which is crucial for operators that wait for streams to end before proceeding.

The “Observer Decoupling” problem

In standard callback patterns, the producer and consumer are often tightly coupled. RxJS decouples them by using the Observer interface. The Producer (Observable) simply calls next, error, or complete on an object, and it doesn’t need to know who is listening or how many listeners there are. This separation of concerns makes testing and scaling much easier.


a. The Observable Constructor and Execution

The most fundamental way to create an Observable is via the new Observable() constructor. This constructor takes a “setup” function (also called the subscriber function) that defines how values are emitted. This function receives a subscriber object, which provides the methods to communicate back to the consumer.

import { Observable } from 'rxjs';

const myObservable$ = new Observable(subscriber => {
  // This code runs only when someone calls .subscribe()
  subscriber.next('Hello');
  subscriber.next('RxJS');

  // Terminal notification: nothing happens after this
  subscriber.complete();

  // This will never be sent
  subscriber.next('Still there?');
});

The subscriber object has three primary methods: next(value) for sending data, error(err) for sending an exception, and complete() for signaling the end of the stream. It is vital to remember that error and complete are terminal. Once either is called, the execution stops, and no further next calls will reach the consumer.

The execution logic inside an Observable can be synchronous or asynchronous. If you call next immediately inside the constructor, the subscriber will receive those values the moment they subscribe, before the subscribe() call even returns. If you use a setTimeout, the values will be pushed asynchronously.


b. The Observer Interface

The Observer is the consumer of the Observable. It is an object (or a set of functions) that “observes” the notifications coming from the stream. A formal Observer object has three optional properties: next, error, and complete.

const myObserver = {
  next: (val: string) => console.log('Value:', val),
  error: (err: any) => console.error('Error:', err),
  complete: () => console.log('Stream is finished!')
};

// Passing the object to subscribe
myObservable$.subscribe(myObserver);

While RxJS used to allow passing three separate functions as arguments to .subscribe(), this approach is now deprecated in favor of passing a single object. This makes the code more readable and prevents confusion about argument order. If you only care about values, you can pass an object with just the next property.

The Observer represents the “Safe Observer” pattern in RxJS. It ensures that even if you try to call next after a complete or error, the consumer won’t receive it, and it ensures that once an error occurs, the subscription is automatically cleaned up.


c. Subscriptions and Teardown Logic

A Subscription is created when you call observable.subscribe(). It represents the ongoing execution of the Observable. The primary purpose of the Subscription object is the unsubscribe() method, which tells the Observable to stop sending data and clean up any resources it is using.

const subscription = interval(1000).subscribe(x => console.log(x));

// Later...
subscription.unsubscribe(); // Stops the interval

To make unsubscribe() actually do something in a custom Observable, you must return a Teardown Function from the constructor. This function is the “undo” button for your Observable. If you started a setInterval, the teardown function should call clearInterval. If you added an event listener, it should call removeEventListener.

const timer$ = new Observable(subscriber => {
  const id = setInterval(() => {
    subscriber.next('Tick');
  }, 1000);

  // RETURN the teardown logic
  return () => {
    console.log('Cleaning up timer...');
    clearInterval(id);
  };
});

When the consumer calls subscription.unsubscribe(), or if the Observable calls complete() or error(), this returned function is automatically triggered. This “automatic cleanup” is one of the most significant advantages of RxJS over manual callback management.


Complete Example Session

// ============================================
// PART 1: DEFINING A CUSTOM OBSERVABLE
// ============================================
import { Observable } from 'rxjs';

const customSource$ = new Observable<number>(subscriber => {
  console.log('--- Observable Execution Started ---');
  let count = 0;

  // ============================================
  // PART 2: PRODUCING VALUES ASYNCHRONOUSLY
  // ============================================
  const intervalId = setInterval(() => {
    count++;
    if (count <= 3) {
      subscriber.next(count); // Push value to observer
    } else {
      subscriber.complete(); // End stream after 3 values
    }
  }, 500);

  // ============================================
  // PART 3: DEFINING TEARDOWN (CLEANUP)
  // ============================================
  return () => {
    console.log('--- Teardown: Clearing Interval ---');
    clearInterval(intervalId);
  };
});

// ============================================
// PART 4: DEFINING THE OBSERVER OBJECT
// ============================================
const observer = {
  next: (val: number) => console.log('Observer received:', val),
  error: (err: any) => console.error('Observer error:', err),
  complete: () => console.log('Observer: Complete!')
};

// ============================================
// PART 5: ACTIVATING THE SUBSCRIPTION
// ============================================
console.log('Subscribing now...');
const sub = customSource$.subscribe(observer);

// ============================================
// PART 6: MANUAL UNSUBSCRIPTION (OPTIONAL)
// ============================================
// Note: In this specific example, the interval will 
// complete itself, but we could also stop it early:
// setTimeout(() => sub.unsubscribe(), 1000);

// ============================================
// PART 7: MULTIPLE SUBSCRIPTIONS ARE INDEPENDENT
// ============================================
setTimeout(() => {
  console.log('Second subscription starting...');
  customSource$.subscribe(val => console.log('Sub 2:', val));
}, 2000);

The example above demonstrates the creation of a custom Observable, the internal logic of an interval, the mandatory teardown logic, and how a terminal complete() notification triggers that teardown. It also shows that every call to .subscribe() triggers a brand new, independent execution of the constructor logic.


Quick Reference

The Observer Interface

MethodRoleTerminal?
next(v)Delivers the next value in the streamNo
error(e)Delivers a JavaScript Error or exceptionYes
complete()Delivers a “finished” notificationYes

Observable Lifecycle States

StateDescriptionTrigger
ColdIdle blueprint, no execution happeningCreation
ActiveExecuting logic, pushing values.subscribe()
ClosedNo longer sending values, cleaned uperror/complete/unsubscribe

Subscription Methods

MethodEffect
unsubscribe()Stops execution and runs teardown
add(sub)Links another subscription to this one (child)
remove(sub)Unlinks a previously added subscription
closedProperty (boolean) indicating if sub is active

Best Practices

โœ… Do This:

// Always return a cleanup function from the constructor
new Observable(sub => { ... return () => cleanup(); });        // โœ…

// Pass an object to subscribe, not positional arguments
source$.subscribe({ next: v => console.log(v) });             // โœ…

// Suffix your Observable variables with $
const clicks$ = fromEvent(btn, 'click');                      // โœ…

// Handle errors at the end of the stream
source$.subscribe({ error: err => handle(err) });             // โœ…

// Complete the subscriber if the producer has a finite end
subscriber.complete();                                        // โœ…

โŒ Don’t Do This:

// Don't call next() after complete()
subscriber.complete(); subscriber.next(5);                    // โŒ

// Don't leak resources by forgetting to return teardown
new Observable(sub => { setInterval(...) });                  // โŒ (Leak!)

// Don't use deprecated positional subscribe arguments
source$.subscribe(v => {}, err => {}, () => {});              // โŒ

// Don't subscribe inside a subscribe
source$.subscribe(v => other$.subscribe());                   // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Zombie IntervalsTeardown function doesn’t clear the interval.Ensure clearInterval is in the return function.
Silent ErrorsNot providing an error handler in the Observer.Always include an error property in your observer object.
Multiple ExecutionsSubscribing 3 times executes constructor 3 times.Use share() if you want to multi-cast.
Next after CompleteLogic continues to run after subscriber.complete().The subscriber stops listening, but code might still run unless you stop it.
Missing UnsubscribeForget to stop infinite observables in components.Use ngOnDestroy or similar lifecycle hooks.

Real-World Examples

1. Custom DOM Event Wrapper

const clicks$ = new Observable(sub => {
  const handler = (e: Event) => sub.next(e);
  document.addEventListener('click', handler);
  return () => document.removeEventListener('click', handler);
});

2. Wrapping Geolocation API

const coords$ = new Observable(sub => {
  const watchId = navigator.geolocation.watchPosition(
    pos => sub.next(pos),
    err => sub.error(err)
  );
  return () => navigator.geolocation.clearWatch(watchId);
});

3. Basic WebSocket Observable

const socket$ = new Observable(sub => {
  const ws = new WebSocket('ws://api.example.com');
  ws.onmessage = (msg) => sub.next(msg.data);
  ws.onerror = (err) => sub.error(err);
  return () => ws.close();
});

4. Finite Random Number Stream

const fiveRandoms$ = new Observable(sub => {
  for(let i=0; i<5; i++) sub.next(Math.random());
  sub.complete();
});

5. Safe Resource Handle

const resource$ = new Observable(sub => {
  const res = openResource();
  sub.next(res);
  return () => res.close();
});

6. Wrapping a Timer

const delay$ = (ms: number) => new Observable(sub => {
  const t = setTimeout(() => { sub.next(); sub.complete(); }, ms);
  return () => clearTimeout(t);
});

7. Polling logic

const poll$ = new Observable(sub => {
  const i = setInterval(async () => {
    const data = await fetch('/api').then(r => r.json());
    sub.next(data);
  }, 5000);
  return () => clearInterval(i);
});

8. Converting Callback to Observable

const legacy$ = new Observable(sub => {
  legacyLib.on('data', d => sub.next(d));
  return () => legacyLib.off('data');
});

9. Custom Sequence

const seq$ = new Observable(sub => {
  sub.next(1); sub.next(2); sub.complete();
});

10. External Signal Unsubscribe

const sub = myObs$.subscribe(v => console.log(v));
cancelBtn.onclick = () => sub.unsubscribe();

Visual

The Triad Interaction

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  OBSERVABLE (The Blueprint)                              โ”‚
โ”‚  "When someone subscribes, start an interval and         โ”‚
โ”‚   return a clearInterval function."                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
               โ”‚
          .subscribe(observer)  โ—„โ”€โ”€โ”€ Consumer initiates
               โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SUBSCRIPTION (The Execution)                            โ”‚
โ”‚  [ Running Interval ] โ”€โ”€โ”€โ”€โ”€โ–บ next(1) โ”€โ”€โ”€โ–บ next(2) ...    โ”‚
โ”‚                                                          โ”‚
โ”‚  When .unsubscribe() is called โ”€โ”€โ”€โ–บ Runs clearInterval   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Teardown Logic Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  OBSERVABLE CONSTRUCTOR                                  โ”‚
โ”‚                                                          โ”‚
โ”‚  (1) Setup: const id = setInterval(...)                  โ”‚
โ”‚                                                          โ”‚
โ”‚  (2) Return: () => clearInterval(id)                     โ”‚
โ”‚               โ”‚                                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                โ”‚
                โ”‚ Triggered by:
                โ”‚ - Manual .unsubscribe()
                โ”‚ - Internal subscriber.complete()
                โ”‚ - Internal subscriber.error()
                โ–ผ
      [ Resource Cleaned Up ]

Terminal Notifications

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  STREAM TIMELINE                                         โ”‚
โ”‚                                                          โ”‚
โ”‚  --next(A)--next(B)--complete()--next(C)                 โ”‚
โ”‚                         โ”‚           โ”‚                    โ”‚
โ”‚                         โ”‚           โ””โ”€ NOPE! (Ignored)   โ”‚
โ”‚                         โ–ผ                                โ”‚
โ”‚                TEARDOWN RUNS HERE                        โ”‚
โ”‚                                                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Constructornew Observable(subscriber => { ... })
Data Methodsubscriber.next(value)
Failure Methodsubscriber.error(error)
Finish Methodsubscriber.complete()
The HookReturn a function for teardown.
The ConsumerObserver object with next/error/complete.
The HandleSubscription object returned by .subscribe().
Cleanupsubscription.unsubscribe().

Key takeaways:

  • Observables are lazy. The code inside the constructor doesn’t run until .subscribe() is called. Each subscription is independent.
  • The Observer is a contract. It expects an object with next, error, and complete methods. This ensures the consumer handles all possible states of the stream.
  • Teardown is the most critical part of custom creation. If your Observable opens a resource (socket, interval, listener), you must return a cleanup function to close it.
  • Error and Complete are terminal. No more data can be sent after an error or completion. RxJS automatically handles the closing of the stream in these cases.
  • Subscriptions are handles to work. They provide the unsubscribe method to manually stop an operation. This is your primary tool for preventing memory leaks in single-page applications.
  • Decoupling is key. The Observable logic shouldn’t know who is observing it; it just calls the methods on the subscriber object.

Remember: Every new Observable should be a self-contained unit that knows how to start itself and, more importantly, how to stop itself. If you write a constructor that doesn’t return a cleanup function, you have likely created a memory leak.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!