Full answer
An operator is a function (source: Observable<T>) => Observable<R>. Most custom operators are just reusable pipe combinations:
export function withStatus<T>(): OperatorFunction<T, Status<T>> {
return (source) => source.pipe(
map((value) => ({ state: 'success', value })),
catchError((error) => of({ state: 'error', error })),
startWith({ state: 'loading' }),
);
}
Guidelines:
- Make it generic, and type input and output with
OperatorFunction<In, Out>orMonoTypeOperatorFunction<T>. - Compose existing operators when possible. Writing a raw
new Observableoperator is rarely needed, and then you must handle unsubscribe, errors and completion yourself. - Keep operators pure: no hidden shared state between subscriptions. Create state inside the returned function (
defer), so each subscription gets its own copy. - Name by intent (
withStatus,pollUntil), and test with marble tests orfakeAsync.
Higher-order patterns in practice: a "higher-order observable" emits Observables. Flattening operators decide how inner streams combine: switchMap (latest wins), mergeMap (all in parallel), concatMap (one by one), exhaustMap (ignore while busy).
A common real problem: process events for many students at once, but keep the events of one student in order (for example, saving edits to one record). Use groupBy(event => event.studentId), which splits the stream into one group per key, then mergeMap(group => group.pipe(concatMap(save))). Different students run in parallel, and each student's saves run one after another. Without groupBy, a global concatMap is too slow, and a global mergeMap can reorder one student's saves.
Memory: groups stay open forever by default. For many keys, close idle groups with groupBy(key, { duration: group => group.pipe(debounceTime(...)) }), or the stream leaks.
// file: operators.ts
import { type Observable, type OperatorFunction, catchError, concatMap, delay, groupBy, map, mergeMap, of, startWith } from 'rxjs';
export type Status<T> =
| { state: 'loading' }
| { state: 'success'; value: T }
| { state: 'error'; message: string };
export function withStatus<T>(): OperatorFunction<T, Status<T>> {
return (source) =>
source.pipe(
map((value): Status<T> => ({ state: 'success', value })),
catchError((error: Error) => of<Status<T>>({ state: 'error', message: error.message })),
startWith<Status<T>>({ state: 'loading' }),
);
}
export interface Edit {
studentId: number;
text: string;
saveMs: number;
}
// Parallel across students, strictly ordered within one student.
export function savePerStudent(save: (edit: Edit) => Observable<string>): OperatorFunction<Edit, string> {
return (source) =>
source.pipe(
groupBy((edit) => edit.studentId),
mergeMap((group) => group.pipe(concatMap((edit) => save(edit)))),
);
}
export const fakeSave = (edit: Edit): Observable<string> =>
of(`saved ${edit.studentId}:${edit.text}`).pipe(delay(edit.saveMs));
// file: main.ts
import { from, throwError, toArray } from 'rxjs';
import { type Edit, fakeSave, savePerStudent, withStatus } from './operators.ts';
const edits: Edit[] = [
{ studentId: 1, text: 'a', saveMs: 60 },
{ studentId: 2, text: 'x', saveMs: 20 },
{ studentId: 1, text: 'b', saveMs: 10 },
{ studentId: 2, text: 'y', saveMs: 30 },
];
from(edits)
.pipe(savePerStudent(fakeSave), toArray())
.subscribe((results) => {
console.log('order of completion', results);
from(['ok']).pipe(withStatus()).pipe(toArray()).subscribe((s) => console.log('success path', JSON.stringify(s)));
throwError(() => new Error('server down')).pipe(withStatus(), toArray()).subscribe((s) => console.log('error path', JSON.stringify(s)));
});RxJS 7.8, type-checked. The script runs in Node 24 and prints the same output on two runs. Timers use distinct delays, so the order does not depend on ties.
Key points
- An operator is a function from Observable to Observable. Compose with `pipe`.
- Use `defer` for per-subscription state. Type with `OperatorFunction`.
- `switchMap`, `mergeMap`, `concatMap` and `exhaustMap` differ in how inner streams combine.
- `groupBy` then `mergeMap` and `concatMap` gives parallel across keys, ordered within each key. Close idle groups.
Common mistakes
- Keeping state in a closure shared by all subscribers of the operator.
- Using a global `mergeMap` when order per key matters.
- Never closing `groupBy` groups for an unbounded set of keys.
Follow-ups
- How would you test this operator with marble tests?
- What happens to an inner error inside `mergeMap` for the other groups?
- How would you add a concurrency limit to `mergeMap`?
Tips
- Show the problem that the operator solves first, then the code.
- Explain the choice of flattening operator in one sentence each.
- Mention the group lifetime. It is a common leak.
Evaluation rubric
- Writes a typed, composable operator.
- Chooses flattening operators correctly.
- Handles per-key ordering and cleanup.