#rxjs #tutorial #beginner

Day 3: Pipeable Operators (map, filter, tap)

Day 3: Pipeable Operators

Observables are useful, but their true power comes from Operators. Operators are functions that take an Observable and return a new Observable with modified data.

We use the .pipe() method to chain operators together.

1. map

Transforms each value. Just like Array.map.

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

of(1, 2, 3).pipe(
  map(x => x * 10)
).subscribe(console.log);
// Output: 10, 20, 30

2. filter

Emits only values that pass a condition. Just like Array.filter.

import { of } from 'rxjs';
import { filter } from 'rxjs/operators';

of(1, 2, 3, 4, 5).pipe(
  filter(x => x % 2 === 0) // Only even numbers
).subscribe(console.log);
// Output: 2, 4

3. tap

Used for side effects (logging, debugging) without affecting the stream. It’s like “peeking” at the data.

import { of } from 'rxjs';
import { map, tap } from 'rxjs/operators';

of(1, 2, 3).pipe(
  tap(val => console.log('Before:', val)), // Log original
  map(val => val + 1),
  tap(val => console.log('After:', val))  // Log transformed
).subscribe();

Chaining Them Together

You can chain as many operators as you want!

import { interval } from 'rxjs';
import { map, filter, take } from 'rxjs/operators';

interval(1000).pipe(
  // 1. Take values: 0, 1, 2, 3, 4, 5...
  filter(num => num % 2 !== 0), // 2. Keep odds: 1, 3, 5...
  map(num => `Number ${num}`),  // 3. Stringify: "Number 1"
  take(3)                       // 4. Stop after 3 emissions
).subscribe(console.log);

// Output (over 5 seconds):
// "Number 1"
// "Number 3"
// "Number 5"
// (Complete)

Homework for Day 3:

  1. Create an observable of numbers 1-10.
  2. Filter out numbers less than 5.
  3. Map the remaining numbers to their square (x * x).
  4. Use tap to log the result.

Day 4: We’ll learn how to control the flow with Filtering Operators!