| | |

RxJS 15 ๐ŸŸฃ Custom Operators & TypeScript โ€” Building reusable, strongly typed pipeable operators and Observable factories

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

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

PatternDefinitionUse Case
Pipeable(source) => ObservableWrapping existing operators
Factory() => ObservableCreating new streams from scratch
Constructornew Observable()Low-level logic, events, timers

TypeScript Generics

SignatureMeaning
<T>Input type
<R>Output type
OperatorFunction<T, R>Standard pipeable signature
Observable<T>Standard observable output

Teardown Checklist

ActionCleanup
setIntervalclearInterval
addEventListenerremoveEventListener
setTimeoutclearTimeout
Websocketsocket.close()
Subscriptionsub.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

PitfallWhy It HappensFix
Memory LeakMissing teardown logicReturn cleanup function
Type MismatchMissing genericsDefine <T, R>
Stream stallsNot calling completeCall subscriber.complete()
Duplicate workCreating logic outside constructorPut logic inside constructor
Loss of errorNot catching exceptionstry/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

ItemValue
Signature(source: Observable<T>) => Observable<R>
Generic types<T, R> for source/output
Teardownreturn () => cleanup()
Constructionnew Observable((sub) => { ... })
Safetysubscriber.next, error, complete

Key takeaways:

  • Custom operators are simple functions. They return an OperatorFunction and 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.

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!