RxJS 02 ๐ฃ Observables, Observers & Subscriptions โ Creating Observables, handling next/error/complete, and teardown logic
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
| Method | Role | Terminal? |
|---|---|---|
next(v) | Delivers the next value in the stream | No |
error(e) | Delivers a JavaScript Error or exception | Yes |
complete() | Delivers a “finished” notification | Yes |
Observable Lifecycle States
| State | Description | Trigger |
|---|---|---|
| Cold | Idle blueprint, no execution happening | Creation |
| Active | Executing logic, pushing values | .subscribe() |
| Closed | No longer sending values, cleaned up | error/complete/unsubscribe |
Subscription Methods
| Method | Effect |
|---|---|
unsubscribe() | Stops execution and runs teardown |
add(sub) | Links another subscription to this one (child) |
remove(sub) | Unlinks a previously added subscription |
closed | Property (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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Zombie Intervals | Teardown function doesn’t clear the interval. | Ensure clearInterval is in the return function. |
| Silent Errors | Not providing an error handler in the Observer. | Always include an error property in your observer object. |
| Multiple Executions | Subscribing 3 times executes constructor 3 times. | Use share() if you want to multi-cast. |
| Next after Complete | Logic continues to run after subscriber.complete(). | The subscriber stops listening, but code might still run unless you stop it. |
| Missing Unsubscribe | Forget 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
| Item | Value |
|---|---|
| Constructor | new Observable(subscriber => { ... }) |
| Data Method | subscriber.next(value) |
| Failure Method | subscriber.error(error) |
| Finish Method | subscriber.complete() |
| The Hook | Return a function for teardown. |
| The Consumer | Observer object with next/error/complete. |
| The Handle | Subscription object returned by .subscribe(). |
| Cleanup | subscription.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, andcompletemethods. 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
unsubscribemethod 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
subscriberobject.
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.
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!