Sub topic 3
Transforming Streams with pipe, map, filter, and tap
An observable on its own only delivers values. Most real work happens between the producer and the subscriber: you reshape payloads, drop values you don't need, and log what passes through. RxJS does this with pipeable operators chained together inside pipe. This chapter covers how pipe builds a chain, how map, filter, and tap behave inside it, and the mistakes intermediate developers make with them most often.
This chapter assumes you know TypeScript generics and arrow functions, and that you have read the earlier chapters on observables, observers, subscriptions, and creation functions such as of and from.
The Working Model of pipe
A pipeable operator is a function that takes an observable and returns a new observable. RxJS types this as OperatorFunction<T, R>, which is a function from Observable<T> to Observable<R>. When you call map(n => n * 2), nothing runs yet. You get back an operator function waiting for a source.
source$.pipe(a, b, c) is function composition. It computes c(b(a(source$))) and returns the outermost observable. The rules that follow from this:
pipenever modifiessource$. It returns a new observable, and you must keep the return value.- No values flow until something subscribes to the result. Building a pipeline is cheap and has no side effects.
- Subscribing to the result subscribes to each inner observable in turn, all the way back to the source. Each subscriber gets its own run of the chain. The chapter on cold and hot observables covers how to share one run.
Values Move One at a Time
map and filter share their names with array methods, but they work on a different axis. Array.prototype.map processes a whole collection before the next step starts. An observable pipeline pushes each value through every operator before the source emits the next one.
import { of, map, filter, tap } from 'rxjs';
const result$ = of(1, 2, 3, 4, 5).pipe(
tap(n => console.log('in', n)),
filter(n => n % 2 === 1),
map(n => n * 10)
);
result$.subscribe(v => console.log('out', v));The output interleaves:
in 1
out 10
in 2
in 3
out 30
in 4
in 5
out 50If you expected all in lines first, you were thinking in arrays. This interleaving is also why operator order matters. A tap placed after filter would log only 1, 3, and 5.
map: Reshaping Each Value
map applies a projection to every next value and emits the result. The projection also receives a zero-based index of the emission.
import { from, map } from 'rxjs';
interface ApiUser {
id: number;
first_name: string;
last_name: string;
}
interface UserView {
id: number;
fullName: string;
position: number;
}
const apiUsers: ApiUser[] = [
{ id: 7, first_name: 'Ada', last_name: 'Lovelace' },
{ id: 9, first_name: 'Alan', last_name: 'Turing' },
];
from(apiUsers)
.pipe(
map((u, index): UserView => ({
id: u.id,
fullName: `${u.first_name} ${u.last_name}`,
position: index + 1,
}))
)
.subscribe(view => console.log(view));Stream map versus array map
A common confusion comes up when a stream emits arrays, as an HTTP call does when it returns Observable<User[]>. The RxJS map receives the whole array as one value. To transform each element, call the array's own map inside it:
import { of, map } from 'rxjs';
const names$ = of([{ name: 'ada' }, { name: 'alan' }]).pipe(
map(users => users.map(u => u.name.toUpperCase()))
);
names$.subscribe(names => console.log(names)); // ['ADA', 'ALAN']Errors thrown inside map
If the projection throws, RxJS catches the exception and sends it to the subscriber as an error notification. The stream then ends, and any later source values are never delivered.
import { of, map } from 'rxjs';
of('1', 'x', '3')
.pipe(
map(s => {
const n = Number(s);
if (Number.isNaN(n)) {
throw new Error(`Not a number: ${s}`);
}
return n;
})
)
.subscribe({
next: n => console.log('value', n),
error: err => console.log('error', err.message),
});
// value 1
// error Not a number: xThe value '3' never arrives. The chapter on error handling shows how catchError recovers from this.
filter: Dropping Values and Narrowing Types
filter passes a value through only when its predicate returns a truthy result. It never changes the value itself. Like map, its predicate receives an index.
The most useful detail for TypeScript users is that filter accepts a type guard, a predicate whose return type is written value is T. With a type guard, the output type narrows. With a plain boolean predicate, it stays the same.
import { of, filter, map } from 'rxjs';
const maybeNames$ = of<(string | null)[]>('ada', null, 'alan', null);
// Without a guard: still Observable<string | null>
const loose$ = maybeNames$.pipe(filter(name => name !== null));
// With a guard: Observable<string>
const strict$ = maybeNames$.pipe(
filter((name): name is string => name !== null),
map(name => name.toUpperCase()) // no null check needed
);
loose$.subscribe(v => console.log('loose', v));
strict$.subscribe(v => console.log('strict', v));tap: Side Effects Without Changing Values
tap runs a function for each notification and passes the value through unchanged. Its return value is ignored. Use it for logging, debugging, analytics, or toggling a loading flag. Keep it out of data transformation.
tap also accepts a partial observer. Since RxJS 7.3, that observer can include lifecycle hooks for subscription, unsubscription, and finalization:
import { interval, take, tap } from 'rxjs';
const ticks$ = interval(500).pipe(
take(3),
tap({
subscribe: () => console.log('subscribed'),
next: v => console.log('tick', v),
error: err => console.log('error', err),
complete: () => console.log('complete'),
unsubscribe: () => console.log('unsubscribed early'),
finalize: () => console.log('finalized'),
})
);
ticks$.subscribe();
// subscribed, tick 0, tick 1, tick 2, complete, finalizedunsubscribe runs only when the consumer unsubscribes before the stream completes or errors. finalize runs on every ending: complete, error, or unsubscribe.
Building Your Own Operators
pipe is also a standalone function. pipe(a, b) combines operators into one reusable OperatorFunction without needing a source. This is the simplest way to name a pipeline you repeat.
import { of, filter, map, pipe, OperatorFunction } from 'rxjs';
export function nonNullish<T>(): OperatorFunction<T | null | undefined, T> {
return filter((v): v is T => v !== null && v !== undefined);
}
export function normalizeTerm(): OperatorFunction<string, string> {
return pipe(
map(s => s.trim()),
map(s => s.toLowerCase())
);
}
of<string | null>(' Angular ', null, ' RxJS')
.pipe(nonNullish(), normalizeTerm())
.subscribe(v => console.log(`[${v}]`));
// [angular]
// [rxjs]Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Calling `source$.pipe(...)` without using the result | Operators seem to have no effect | Assign or return the new observable |
| Building a pipeline but never subscribing | No logs from `tap`, no requests sent | Subscribe, or use the async pipe |
| Mutating the input object inside `map` | Other subscribers see changed data | Return a new object with spread syntax |
| Doing side effects in `map` | Effects hidden inside data transforms | Move them to `tap` |
| Relying on `tap`'s return value | Value unchanged downstream | Use `map` to change values |
| Using RxJS `map` on an array-emitting stream to change elements | Whole array treated as one item | Call `Array.prototype.map` inside the RxJS `map` |
| Boolean predicate where narrowing is needed | Type still includes `null` | Write a `value is T` type guard |
| Wrong operator order | Logs or counts include dropped values | Place `filter` before steps that should skip dropped values |
Exercise
Given of(3, 8, 5, 12).pipe(map(n => n * 2), filter(n => n > 10), tap(n => console.log(n))), what is logged when you subscribe, and what changes if filter is moved before map without editing its predicate?
Show answer
As written, values double to 6, 16, 10, 24, and filter keeps those above 10, so 16 and 24 are logged. With filter first, it keeps the original values above 10, which is only 12. Map then doubles it, so only 24 is logged.
Exercise
A colleague writes this.items$.pipe(tap(items => items.sort())) to show items in sorted order. Name two problems with this code and give a corrected version.
Show answer
First, Array.prototype.sort sorts in place, so it mutates the emitted array that other subscribers or the producer may also hold. Second, transforming data in tap hides intent; tap is for side effects, and this only works because of the mutation. A corrected version is this.items$.pipe(map(items => [...items].sort())), which copies the array and returns a sorted copy. If the original pipe result was also never assigned, a third problem is that the new observable is discarded.
Exercise
Write a reusable operator positiveOnly() that takes a stream of number | null and emits only numbers greater than zero, typed as OperatorFunction<number | null, number>.
Show answer
function positiveOnly(): OperatorFunction<number | null, number> { return filter((n): n is number => n !== null && n > 0); } The type guard narrows the output to number, and the extra condition drops zero and negative values.