Sub topic 3
Transforming Streams with pipe, map, filter, and tap
This chapter assumes you know TypeScript arrow functions and generics, and that you can create and subscribe to an observable. Here you learn to reshape the values a stream emits without writing a new observable by hand.
The working model of pipe
An operator is a function that takes an observable and returns a new one. The pipe method chains operators from left to right. Each operator subscribes to the one before it and passes along whatever it produces.
Two facts follow from this model:
pipenever changes the source. It returns a new observable, sosource$.pipe(map(...))with no assignment has no effect.pipeis lazy. Nothing runs until something subscribes to the result.
map, filter, and tap together
import { of, map, filter, tap } from 'rxjs';
const source$ = of(1, 2, 3, 4, 5);
const result$ = source$.pipe(
tap(v => console.log('in', v)),
filter(v => v % 2 === 1),
map(v => v * 10)
);
result$.subscribe(v => console.log('out', v));The output is in 1, out 10, in 2, in 3, out 30, in 4, in 5, out 50. Every value goes through the whole chain before the next value starts. Each operator does a different job:
| Operator | Receives | Returns downstream | Use it for |
|---|---|---|---|
| `map(fn)` | each value | `fn(value)` | changing the shape of a value |
| `filter(pred)` | each value | the value only if `pred` is true | dropping values you don't need |
| `tap(fn)` | each value | the same value, unchanged | logging and other side effects |
Typing with filter
In TypeScript, filter narrows the type only if you pass a type guard:
import { of, filter, map } from 'rxjs';
const names$ = of<(string | null)[]>('ada', null, 'linus').pipe(
filter((n): n is string => n !== null),
map(n => n.toUpperCase())
);
names$.subscribe(n => console.log(n));If you leave out the n is string annotation, n inside map stays string | null, and the compiler rejects toUpperCase.
Common errors
- Using tap to transform.
tapthrows away its callback's return value.tap(x => x * 2)passes the originalxdownstream unchanged. - Side effects in map. If
mapsaves to a field or writes to storage, your intent is harder to read. Put side effects intapand keepmappure. - Mutating inside map.
map(user => { user.active = true; return user; })changes the object that every other holder of it sees. Return a copy instead:map(user => ({ ...user, active: true })). - Forgetting the subscription. A pipeline with no subscriber, whether from
subscribeor the async pipe, never runs. Yourtaplogs never appear. - Old patch syntax. Code like
source$.map(...)is from RxJS 5. Since RxJS 6, operators are imported from'rxjs'and passed topipe.
Exercise
Given of(2, 5, 8, 11), write a pipe that logs each incoming value, keeps only values greater than 4, and emits each kept value as a string such as "Value: 5". What does the subscriber receive?
Show answer
Use source$.pipe(tap(v => console.log(v)), filter(v => v > 4), map(v => Value: ${v})). The subscriber receives "Value: 5", "Value: 8", and "Value: 11". The log shows all four inputs, because tap comes before filter.
Exercise
A teammate writes source$.pipe(tap(x => x + 1)).subscribe(console.log) on of(1, 2) and expects 2 and 3. What prints, and how do you fix it?
Show answer
It prints 1 and 2, because tap ignores its callback's return value. Replace tap with map(x => x + 1).