RxJS 15 ๐ฃ Custom Operators & TypeScript โ Building reusable, strongly typed pipeable operators and Observable factories
Custom operators in RxJS are not a special library feature; they are a direct consequence of the observable’s functional design. Because every operator in the RxJS library is simply a function that takes an Observable and returns a new Observable, your own custom operators are treated as first-class citizens. You build them by either composing existing operators via a pipe, or by using the Observable constructor to manually implement the subscriber logic when a standard composition cannot achieve the desired result.
This chapter details the anatomy of these operators. It starts with the operator signatureโthe higher-order function patternโand demonstrates how to use TypeScript generics to ensure type safety through the pipeline. It then moves to the Observable constructor, which is where you must handle the subscription logic and teardown manually. The final sections cover the structural requirements of custom logic, including how to properly forward errors and how to manage the lifecycle of the inner subscription without introducing memory leaks.
Key point: A custom operator is a function that returns an OperatorFunction<T, R>, and a custom Observable factory returns an Observable<T>; the core requirement is to handle the subscribe call, forward notifications correctly, and ensure teardown logic is registered to prevent resource leakage.
Why operators exist
Abstraction of complexity. A chain of five operatorsโfilter, map, scan, debounceTime, and catchErrorโis a complex piece of logic. If it appears in ten components, it is a maintenance burden. Wrapping that chain in a custom operator converts a detailed imperative implementation into a single declarative word.
Type consistency. TypeScript’s power lies in strict flow. A custom operator allows you to enforce that a stream of User objects always results in a stream of ViewModel objects. Without the abstraction, developers might miss a map or use an incorrect interface, leading to runtime errors that the compiler could have caught.
Encapsulation of side effects. Logic that involves tap, finalize, or manual subscription management should not be scattered across the codebase. By encapsulating these side effects inside a custom operator, you guarantee that every subscriber gets the same logging, the same cleanup, and the same error handling.
Standardization of patterns. Teams often develop preferred ways of doing things, such as “retry three times with exponential backoff.” Creating a standard retryWithBackoff operator ensures that every network request uses the same policy, preventing “policy drift” where different parts of the app behave inconsistently under failure.
Interoperability with existing streams. Custom operators are just functions. They compose seamlessly with the thousands of operators already in RxJS. You do not need to implement new “lifting” logic or integrate with the internal library mechanism; you simply write a function, and the pipe() method treats it like any native operator.
a. Building pipeable operators via composition
The most common way to build an operator is to pipe existing ones. This is effectively “macro” programming: you define a function that performs the pipe internally. The signature must match (source: Observable<T>) => Observable<R>. TypeScript provides the OperatorFunction<T, R> type to make this cleaner.
import { Observable, OperatorFunction, pipe } from "rxjs";
import { map, filter } from "rxjs/operators";
// The signature: a function returning an OperatorFunction
export function filterAndMap<T, R>(
predicate: (value: T) => boolean,
mapper: (value: T) => R
): OperatorFunction<T, R> {
return (source: Observable<T>) => source.pipe(
filter(predicate),
map(mapper)
);
}
This pattern is safe because it relies entirely on the internal implementation of the operators you compose. You inherit their error handling, cancellation logic, and subscription management. The only responsibility you have is to ensure the types T and R align.
b. The Observable constructor pattern
When you need behavior that no existing operator provides, you must use the new Observable() constructor. This gives you direct access to the subscriber object. This is a manual, low-level approach where you define exactly what happens when someone subscribes, what happens when a value is emitted, and what happens when the subscriber unsubscribes.
import { Observable } from "rxjs";
// A custom factory that emits a value, then completes
export function emitOnce<T>(value: T): Observable<T> {
return new Observable<T>((subscriber) => {
subscriber.next(value);
subscriber.complete();
// No teardown needed as this is synchronous and finite
});
}
The logic inside the constructor is the “body” of your Observable. It runs every time someone calls subscribe(). This is why you must perform setupโlike adding event listeners or starting timersโinside this function.
c. Managing teardown and subscriptions
When using the Observable constructor, you are responsible for returning a teardown function or a Subscription. If your operator starts a processโlike a setInterval or an event listenerโthat process will leak if you do not stop it when the subscriber unsubscribes. The return value of the observable’s setup function is executed automatically upon unsubscribe.
import { Observable } from "rxjs";
// A custom operator that tracks a timer
export function intervalManual(period: number): Observable<number> {
return new Observable<number>((subscriber) => {
let count = 0;
const intervalId = setInterval(() => {
subscriber.next(count++);
}, period);
// Teardown function: stops the interval when the subscription ends
return () => clearInterval(intervalId);
});
}
If you do not return this function, the setInterval will run for the life of the application, regardless of whether the subscriber has called unsubscribe(). This is the most common cause of memory leaks in custom RxJS operators.
Complete Example Session
// ============================================
// PART 1: COMPOSING PIPEABLE OPERATORS
// ============================================
import { OperatorFunction, pipe } from "rxjs";
import { map, filter } from "rxjs/operators";
export function keepAndTransform<T, R>(
predicate: (v: T) => boolean,
transform: (v: T) => R
): OperatorFunction<T, R> {
return pipe(
filter(predicate),
map(transform)
);
}
// ============================================
// PART 2: THE OBSERVABLE CONSTRUCTOR
// ============================================
import { Observable } from "rxjs";
function myCustomInterval(ms: number): Observable<number> {
return new Observable<number>((subscriber) => {
let i = 0;
const id = setInterval(() => subscriber.next(i++), ms);
return () => clearInterval(id); // Important: Cleanup!
});
}
// ============================================
// PART 3: HANDLING ERRORS
// ============================================
export function safelyEmit<T>(value: T): Observable<T> {
return new Observable<T>((subscriber) => {
try {
subscriber.next(value);
subscriber.complete();
} catch (err) {
subscriber.error(err);
}
});
}
// ============================================
// PART 4: WRAPPING EXISTING OPERATORS
// ============================================
import { tap, catchError, of } from "rxjs";
export const logAndRecover = <T>(msg: string): OperatorFunction<T, T> =>
pipe(
tap(v => console.log(msg, v)),
catchError(err => {
console.error("Recovering from:", err);
return of();
})
);
// ============================================
// PART 5: THE LIFTING PATTERN (ADVANCED)
// ============================================
// Usually avoid 'lift' unless you are building a library,
// but it is the raw way to intercept the subscriber.
class MyOperatorOperator<T, R> {
call(subscriber: any, source: any) {
return source.subscribe(subscriber);
}
}
// ============================================
// PART 6: TYPING THE OPERATOR
// ============================================
// Use generics strictly to ensure the input/output contract
export function mapStringLength(): OperatorFunction<string, number> {
return map(s => s.length);
}
// ============================================
// PART 7: COMPOSING WITH STATE
// ============================================
import { scan } from "rxjs/operators";
export function runningTotal(): OperatorFunction<number, number> {
return scan((acc, curr) => acc + curr, 0);
}
// ============================================
// PART 8: CUSTOM FACTORY
// ============================================
import { fromEvent } from "rxjs";
export function clickCoordinates(): Observable<{x: number, y: number}> {
return new Observable(sub => {
const handler = (e: MouseEvent) => sub.next({ x: e.clientX, y: e.clientY });
document.addEventListener("click", handler);
return () => document.removeEventListener("click", handler);
});
}
// ============================================
// PART 9: CONDITIONAL EMISSION
// ============================================
export function filterNil<T>(): OperatorFunction<T | null | undefined, T> {
return filter((v): v is T => v !== null && v !== undefined);
}
// ============================================
// PART 10: COMPLEX TEARDOWN
// ============================================
export function customWithTeardown(fn: () => void): Observable<any> {
return new Observable(() => {
return () => fn(); // Ensure the function runs
});
}
The parts above cover the spectrum of custom operator creation: the composition of existing operators using pipe, the manual construction of Observables using the constructor, rigorous type management with generics, essential teardown logic, and the creation of custom Observable factories that emit based on external events.
Quick Reference
Operator Anatomy
| Pattern | Definition | Use Case |
|---|---|---|
| Pipeable | (source) => Observable | Wrapping existing operators |
| Factory | () => Observable | Creating new streams from scratch |
| Constructor | new Observable() | Low-level logic, events, timers |
TypeScript Generics
| Signature | Meaning |
|---|---|
<T> | Input type |
<R> | Output type |
OperatorFunction<T, R> | Standard pipeable signature |
Observable<T> | Standard observable output |
Teardown Checklist
| Action | Cleanup |
|---|---|
setInterval | clearInterval |
addEventListener | removeEventListener |
setTimeout | clearTimeout |
Websocket | socket.close() |
Subscription | sub.unsubscribe() |
Best Practices
โ Do This:
// Define explicit return types
export const mapToLength = (): OperatorFunction<string, number> => map(x => x.length); // โ
// Return teardown functions
return () => clearInterval(id); // โ
// Use pipe for compositions
return pipe(filter(x => !!x), map(x => x.data)); // โ
// Validate inputs
if (period < 0) subscriber.error("Negative period"); // โ
// Use generics
export function mapTo<T, R>(val: R): OperatorFunction<T, R> { ... } // โ
โ Don’t Do This:
// Forget to return a teardown logic
setInterval(() => sub.next(), 100); // โ
// Use 'any' type for inputs/outputs
export const myOp = (source: any) => source.pipe(...); // โ
// Modify source directly (Side effects)
source.data = 5; // โ
// Create infinite loops in custom constructors
sub.next(1); sub.next(1); // โ
// Throw errors in constructors without subscriber.error
throw new Error("fail"); // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Memory Leak | Missing teardown logic | Return cleanup function |
| Type Mismatch | Missing generics | Define <T, R> |
| Stream stalls | Not calling complete | Call subscriber.complete() |
| Duplicate work | Creating logic outside constructor | Put logic inside constructor |
| Loss of error | Not catching exceptions | try/catch in constructor |
Real-World Examples
1. Filter out null/undefined
const filterNil = <T>() => filter((v): v is T => v != null);
2. Retry with delay
const retryWithDelay = (delay: number) => retry({ delay });
3. Log values
const log = <T>(tag: string) => tap<T>(v => console.log(tag, v));
4. Map to object property
const pluck = <T, K extends keyof T>(key: K) => map((x: T) => x[key]);
5. Convert click to coordinate
const clickCoords = () => fromEvent<MouseEvent>(document, 'click').pipe(map(e => ({x: e.x, y: e.y})));
6. Toggle boolean
const toggle = () => scan((acc) => !acc, false);
7. Ensure non-empty
const requireValue = <T>() => filter<T>(v => !!v);
8. Buffer until event
const bufferUntil = <T>(notifier: Observable<any>) => buffer(notifier);
9. Error-safe map
const safeMap = <T, R>(fn: (v: T) => R) => map((v: T) => { try { return fn(v); } catch { return null; }});
10. Throttle with custom logic
const customThrottle = (ms: number) => throttleTime(ms, asyncScheduler, { leading: true, trailing: false });
Visual
The Pipeable Chain
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ OPERATOR COMPOSITION โ
โ โ
โ source โโโบ [ Operator A ] โโโบ [ Operator B ] โโโบ sink โ
โ โ
โ A custom operator is just a wrapper: โ
โ fn = (source) => source.pipe(A, B) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Observable Constructor Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CONSTRUCTOR LOGIC โ
โ โ
โ subscribe() called โ
โ โ โ
โ โผ (constructor runs) โ
โ setup (add listener/interval) โ
โ โ โ
โ โผ (events happen) โ
โ subscriber.next() โโโบ emitted values โ
โ โ โ
โ โผ (unsubscribe called) โ
โ teardown (cleanup interval/listener) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Operator Ownership
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ OWNERSHIP DIAGRAM โ
โ โ
โ Pipeable Op: โ
โ Uses internal operators to manage subscription โ
โ โ
โ Custom Observable: โ
โ You are the owner. You manage the subscriber. โ
โ If you don't clean up, no one will. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Signature | (source: Observable<T>) => Observable<R> |
| Generic types | <T, R> for source/output |
| Teardown | return () => cleanup() |
| Construction | new Observable((sub) => { ... }) |
| Safety | subscriber.next, error, complete |
Key takeaways:
- Custom operators are simple functions. They return an
OperatorFunctionand are completely interoperable with the standard library. - Always handle teardown. If you allocate a resource (timer, socket, event listener) in a custom Observable constructor, return the cleanup function to prevent memory leaks.
- Use TypeScript generics. Defining
<T, R>ensures your custom operators participate in type checking, preventing bugs where the output type doesn’t match the expectation. - Prefer composition. Build custom operators by piping existing ones whenever possible; the built-in operators are optimized and handle edge cases you might miss.
- Encapsulate complexity. Use custom operators to hide implementation details and improve code readability, turning imperative logic into declarative streams.
Remember: A custom operator is a contract. You promise to accept an input stream and produce an output stream. When you use the Observable constructor, you become responsible for that contract’s entire lifecycle, including errors and cleanup. Keep your custom operators small, focused, and strongly typed, and your code will benefit from the same robust guarantees as the built-in library.
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!