1. RxJS Observables & Streams

Think in streams — the building block of reactive Angular

Open a web app. A user types into a search box. Each keystroke is an event. The browser fires input events, one after another, forming a stream — an ordered sequence of values over time. RxJS gives you a powerful vocabulary for describing what should happen to that stream: debounce it, filter it, transform it, combine it with other streams, and ultimately subscribe to get results.

If you've used Promises, you already understand half the idea. A Promise represents one future value. An Observable represents zero or more values over time — possibly infinite, possibly asynchronous. That's the leap.

What Is an Observable?

An Observable is a lazy producer of values. It doesn't do anything until someone subscribes to it. Once subscribed, it can emit three kinds of notifications:

Notification Meaning Can happen...
next A new value is available Zero or more times
error Something went wrong — the stream is dead At most once
complete No more values — the stream is done At most once

After either error or complete, the Observable never emits again.

Lazy by default

An Observable is like a function definition — it describes what will happen, but nothing runs until you call it. Subscribing is the "call." This is fundamentally different from Promises, which start executing the moment you create them.

Creating Observables

RxJS provides creation functions for common patterns. Here are the ones you'll use daily:

of — emit fixed values, then complete

import { of } from 'rxjs';

const greeting$ = of('hello', 'world');

greeting$.subscribe({
  next: value => console.log(value),
  complete: () => console.log('done')
});
// hello
// world
// done

The $ suffix is a convention — it marks a variable as an Observable. You'll see it everywhere in Angular codebases.

from — convert arrays, promises, or iterables

import { from } from 'rxjs';

// From an array
const numbers$ = from([10, 20, 30]);
numbers$.subscribe(n => console.log(n));
// 10
// 20
// 30

// From a Promise
const data$ = from(fetch('/api/users').then(r => r.json()));
data$.subscribe(users => console.log(users));

interval and timer — time-based streams

import { interval, timer } from 'rxjs';

// Emit 0, 1, 2, 3... every second (never completes)
const ticks$ = interval(1000);

// Wait 2 seconds, then emit 0
const delayed$ = timer(2000);

// Wait 1 second, then emit every 500ms
const polling$ = timer(1000, 500);

fromEvent — DOM events as streams

import { fromEvent } from 'rxjs';

const clicks$ = fromEvent(document, 'click');
clicks$.subscribe(event => console.log('clicked at', event.clientX));

const input = document.querySelector('input');
const keystrokes$ = fromEvent(input, 'input');
keystrokes$.subscribe(e => console.log((e.target as HTMLInputElement).value));

This is where RxJS starts to shine. Every DOM event — clicks, scrolls, resizes, keypresses — becomes a stream you can transform with the same operators.

Subscribing and Unsubscribing

Subscribing returns a Subscription object. You use it to stop listening:

import { interval } from 'rxjs';

const counter$ = interval(1000);

const subscription = counter$.subscribe(n => console.log(n));
// 0, 1, 2, 3...

// Stop after 5 seconds
setTimeout(() => {
  subscription.unsubscribe();
  console.log('stopped');
}, 5000);

Memory leaks

If you subscribe to an Observable that never completes (like interval or fromEvent) and forget to unsubscribe, the callback keeps running forever. In Angular, this means leaked subscriptions when components are destroyed. We'll cover how Angular solves this with the async pipe and takeUntilDestroyed in a later article.

Building Your Own Observable

Sometimes the creation functions aren't enough. You can build a custom Observable from scratch:

import { Observable } from 'rxjs';

const custom$ = new Observable<number>(subscriber => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);

  setTimeout(() => {
    subscriber.next(4);
    subscriber.complete();
  }, 1000);

  // Teardown logic — runs on unsubscribe
  return () => {
    console.log('cleaned up');
  };
});

custom$.subscribe({
  next: val => console.log(val),
  complete: () => console.log('done')
});
// 1 (sync)
// 2 (sync)
// 3 (sync)
// 4 (after 1s)
// done
// cleaned up

The function you pass to new Observable() is the subscriber function. It receives a Subscriber object and can call next, error, or complete on it. The return value is a teardown function that cleans up resources when the subscription ends.

Cold vs. Hot Observables

This distinction trips up everyone at first.

Cold Observables

A cold Observable creates a new producer for each subscriber. Each subscriber gets its own independent stream.

import { Observable } from 'rxjs';

const cold$ = new Observable<number>(subscriber => {
  console.log('producer created');
  subscriber.next(Math.random());
  subscriber.complete();
});

cold$.subscribe(val => console.log('A:', val));
// producer created
// A: 0.7234...

cold$.subscribe(val => console.log('B:', val));
// producer created
// B: 0.1891...   <-- different value! different producer

Most RxJS creation functions produce cold Observables. of, from, interval, and HTTP requests in Angular are all cold.

Hot Observables

A hot Observable shares a single producer among all subscribers. Late subscribers miss values that were emitted before they subscribed.

import { fromEvent } from 'rxjs';

// The DOM is the shared producer — there's only one document
const clicks$ = fromEvent(document, 'click');

// Subscriber A starts listening
clicks$.subscribe(() => console.log('A heard a click'));

// 3 seconds later, subscriber B starts listening
setTimeout(() => {
  clicks$.subscribe(() => console.log('B heard a click'));
}, 3000);

// Clicks in the first 3 seconds: only A hears them
// Clicks after 3 seconds: both A and B hear them

Cold vs. Hot — the analogy

A cold Observable is like a YouTube video — each viewer gets their own playback from the beginning. A hot Observable is like a live broadcast — you see whatever is happening when you tune in.

Try It Yourself — Observable Timeline

Pick a source type, hit Subscribe, and watch values arrive on the timeline. Try interval or fromEvent and then Unsubscribe to see the stream stop. Notice how of and timer complete on their own.

Event log

The Observable Pipeline

The real power of RxJS is piping — chaining operators to transform a stream step by step. Every operator takes an Observable in and returns a new Observable out, without modifying the original.

import { fromEvent } from 'rxjs';
import { map, filter, debounceTime } from 'rxjs/operators';

const input = document.querySelector<HTMLInputElement>('#search');

const searchTerms$ = fromEvent(input, 'input').pipe(
  map(event => (event.target as HTMLInputElement).value),  // extract text
  map(text => text.trim()),                                 // clean it
  filter(text => text.length >= 3),                         // ignore short input
  debounceTime(300)                                         // wait for typing pause
);

searchTerms$.subscribe(term => console.log('Search for:', term));

Read this pipeline top to bottom: raw DOM events flow in at the top, and clean, debounced search strings come out at the bottom. Each step is a pure transformation. This is declarative — you describe what should happen, not how to manage the state.

Observables in Angular

Angular is built on RxJS. You'll encounter Observables in:

Where What returns an Observable
HttpClient http.get(), http.post(), etc.
Router ActivatedRoute.params, Router.events
Forms FormControl.valueChanges, statusChanges
@Output() EventEmitter (which extends Subject)
NgRx Store.select(), Actions, Effects

Here's a taste of how Angular's HttpClient returns an Observable:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

interface User {
  id: number;
  name: string;
  email: string;
}

@Component({
  selector: 'app-user-list',
  template: `
    <ul>
      <li *ngFor="let user of users">{{ user.name }}</li>
    </ul>
  `
})
export class UserListComponent implements OnInit {
  users: User[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get<User[]>('/api/users').subscribe(users => {
      this.users = users;
    });
  }
}

The HTTP request is a cold Observable — it doesn't fire until you subscribe, and each subscription makes a new request.

Putting It Together: A Real Pattern

Here's a realistic search-as-you-type pattern that combines several ideas:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, filter } from 'rxjs/operators';

interface SearchResult {
  id: number;
  title: string;
}

@Component({
  selector: 'app-search',
  template: `
    <input [formControl]="searchControl" placeholder="Search...">
    <ul>
      <li *ngFor="let result of results">{{ result.title }}</li>
    </ul>
  `
})
export class SearchComponent implements OnInit, OnDestroy {
  searchControl = new FormControl('');
  results: SearchResult[] = [];
  private subscription: Subscription;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.subscription = this.searchControl.valueChanges.pipe(
      debounceTime(300),                              // wait for pause in typing
      distinctUntilChanged(),                          // skip if same as last term
      filter(term => term.length >= 2),               // need at least 2 chars
      switchMap(term =>                                // cancel previous request
        this.http.get<SearchResult[]>(`/api/search?q=${term}`)
      )
    ).subscribe(results => {
      this.results = results;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();   // prevent memory leak
  }
}

This is 15 lines of reactive code replacing what would be dozens of lines of imperative code — managing timers, tracking previous values, cancelling in-flight requests, cleaning up event listeners. The Observable pipeline handles all of it.

What's Next

You've seen what Observables are, how to create them, and how the pipeline model works. The next article dives deep into the operators — map, switchMap, mergeMap, concatMap, and the rest of the toolkit that makes RxJS so powerful.