#rxjs #tutorial #intermediate

Day 5: Combination Operators (merge, concat, combineLatest)

Day 5: Combination Operators

Rarely does an app rely on a single data source. We often need to combine HTTP calls, user events, and timers.

1. merge

Combines multiple observables into one. Like cars merging onto a highway—first come, first served. Use case: Doing the same action when Button A OR Button B is clicked.

import { merge, fromEvent } from 'rxjs';

const clickA$ = fromEvent(btnA, 'click');
const clickB$ = fromEvent(btnB, 'click');

merge(clickA$, clickB$).subscribe(() => {
  console.log('Either A or B was clicked!');
});

2. concat

Subscribes to observables in order. It waits for the first to complete before starting the second. Use case: Show a loading spinner, THEN fetch data.

import { concat, of } from 'rxjs';
import { delay } from 'rxjs/operators';

const task1$ = of('Task 1').pipe(delay(2000));
const task2$ = of('Task 2');

concat(task1$, task2$).subscribe(console.log);
// Output: (waits 2s) "Task 1", then immediately "Task 2"

3. combineLatest

Emits whenever ANY observable emits, providing the latest value from EVERY observable as an array. Use case: Filters. When ‘Category’ OR ‘Search’ changes, give me the current state of both.

import { combineLatest, of } from 'rxjs';

const color$ = of('Red', 'Blue');
const size$  = of('Small', 'Large');

// Warning: waiting for both to emit at least once
combineLatest([color$, size$]).subscribe(([color, size]) => {
  console.log(`Color: ${color}, Size: ${size}`);
});

4. forkJoin

Wait for ALL observables to complete, then emit their last values. This is like Promise.all. Use case: Fire 3 API calls, wait for all to finish before showing the UI.

import { forkJoin, of } from 'rxjs';

forkJoin({
  user: of({ id: 1, name: 'Jack' }),
  settings: of({ theme: 'dark' })
}).subscribe(result => {
  console.log(result.user.name, result.settings.theme);
});

Homework for Day 5:

  1. Create two Observables using timer. One emits after 1s, one after 2s.
  2. Use merge to see them log at 1s and 2s.
  3. Use forkJoin to see them log only at 2s (as an array).

Day 6: We learn to count and accumulate with Transformation Operators!