#rxjs #tutorial #beginner

Day 1: Observables, Observers & Subscriptions

Day 1: The Reactive Mindset

Welcome to the RxJS Reactive Masterclass. Over the next 10 days, we will master asynchronous programming in JavaScript.

What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. Think of it as “LoDash for events”.

The Core Concepts

1. Observable (The Stream)

An Observable is a collection of values over time.

  • An array [1, 2, 3] is a collection of values in space (memory).
  • An Observable is a stream of values in time.

2. Observer (The Listener)

An Observer is just an object with 3 callback functions:

  • next(value): Called when a new value is emitted.
  • error(err): Called if an error occurs.
  • complete(): Called when the stream is finished.

3. Subscription (The Connection)

An Observable does nothing until you subscribe to it. It’s like a YouTube video; it doesn’t play until you hit play.

Your First Observable

Let’s create a simple observable that emits “Hello”, “World”, and then completes.

import { Observable } from 'rxjs';

const myObservable$ = new Observable((subscriber) => {
  subscriber.next('Hello');
  subscriber.next('World');
  subscriber.complete();
});

Note: It’s a convention to append $ to variables holding Observables.

Subscribing

Now, let’s listen to it.

myObservable$.subscribe({
  next: (value) => console.log('Got value:', value),
  error: (err) => console.error('Error:', err),
  complete: () => console.log('Done!'),
});

Output:

Got value: Hello
Got value: World
Done!

Cleaning Up

Subscriptions can be cancelled (unsubscribed) to stop listening and prevent memory leaks.

const sub = interval$.subscribe(...);

// Later...
sub.unsubscribe();

Homework for Day 1:

  1. Create an Observable that emits numbers 1 to 5.
  2. Subscribe to it and log the values.
  3. Try creating an Observable that emits a value every second (hint: setInterval).

See you in Day 2 for Creation Operators!