Course contentsShow
← JavaScript
Lesson 2130 of 2,72344. Reactive PatternsFree lesson

Subscribing to Observables

The subscribe method and its observer object with next, error, and complete handlers.

Subscribing to Observables

You'll learn how to activate an Observable by subscribing with handlers for data, errors, and completion.

Why Subscribe Matters

Creating an Observable doesn't do anything by itself—it's just a recipe. Subscribing is what starts the Observable, like pressing "play" on a streaming service. When you subscribe, you provide an observer object that tells the Observable what to do when it emits values, encounters errors, or completes.

The Observer Object

The subscribe method accepts an observer object with up to three optional methods:

observable.subscribe({
  next: (value) => {
    // Handle each emitted value
    console.log('Received:', value);
  },
  error: (err) => {
    // Handle any error
    console.error('Error occurred:', err);
  },
  complete: () => {
    // Handle completion signal
    console.log('Stream completed');
  }
});

How Each Handler Works

  • next(value): Called each time the Observable emits a value. This is where you process the data.
  • error(err): Called if something goes wrong. Once error fires, the stream stops—no more next or complete.
  • complete(): Called when the Observable finishes successfully with no more values coming.

Think of it like a conversation: next is each sentence spoken, error is hanging up abruptly, and complete is saying "goodbye" properly.

import { of } from 'rxjs';

const numbers$ = of(1, 2, 3);

numbers$.subscribe({
  next: (n) => console.log(n),
  complete: () => console.log('Done!')
});
// Logs: 1, 2, 3, Done!

Key Takeaway: Subscribing activates an Observable by providing next, error, and complete handlers that define how to respond to emitted values, errors, and completion signals.