Learn Angular · 6/14

Reactive Programming Basics: Embracing RxJS

8 min read

Course: Angular
Topic ID: 6
Difficulty: Intermediate 🧠


👋 Introduction

Welcome to the heart of Angular’s asynchronous architecture.

In previous modules, we handled data statically or via simple interactions. However, modern web applications are dynamic. Data arrives unpredictably: a user clicks a button, a WebSocket message arrives, or an HTTP request completes.

To manage this complexity, Angular relies heavily on RxJS (Reactive Extensions for JavaScript).

RxJS is a library for composing asynchronous and event-based programs by using observable sequences. Think of it as a way to treat events as collections.

Fun Fact: The Reactive Extensions (Rx) library was originally created by Erik Meijer at Microsoft for .NET in 2009. It was so mathematically sound and useful that it was ported to Java (RxJava), JavaScript (RxJS), Swift (RxSwift), and many others. It is now a cross-language standard.


1. Understanding the Observer Pattern: Observables vs. Promises

Definition

The Observer Pattern is a software design pattern in which an object, called the Subject (or Producer), maintains a list of its dependents, called Observers (or Consumers), and notifies them automatically of any state changes, usually by calling one of their methods.

In RxJS, the core primitive is the Observable.

The Problem

In standard JavaScript, we often use Promises to handle asynchronous operations.

  • Promise: "I promise to return one value (or an error) at some point in the future."
  • Limitation: A Promise cannot handle a stream of multiple events (like mouse movements or a WebSocket chat stream). It resolves once and dies.

The Solution: Observables

An Observable is a function that creates a stream of values to an observer over time.

  • Promise: Push strategy. Returns a single value. Not cancellable.
  • Observable: Push strategy. Returns zero to infinite values. Cancellable (lazy).

🧐 Academic Comparison

Feature Promise Observable
Cardinality Single Value Multiple Values (Stream)
Execution Eager (executes immediately) Lazy (executes only on subscription)
cancellation Not standard Cancellable via unsubscribe
Operations then, catch map, filter, reduce, retry, etc.

💻 Industry Practice: Creating Your First Observable

To work with RxJS, we import from the rxjs package.

typescript
import { Observable } from 'rxjs';

// 1. Create an Observable
// The '$' suffix is a naming convention for Observables (Finnish Notation).
const numberStream$ = new Observable<number>((subscriber) => {
  console.log('Stream started');
  
  // Push values to the subscriber
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
  
  // Signal completion
  subscriber.complete();
});

// 2. Execute (Subscribe)
// Nothing happens until we call .subscribe()
console.log('Before subscription');

numberStream$.subscribe({
  next: (value) => console.log(`Received: ${value}`),
  error: (err) => console.error(`Error: ${err}`),
  complete: () => console.log('Stream finished'),
});

console.log('After subscription');

Output:

text
Before subscription
Stream started
Received: 1
Received: 2
Received: 3
Stream finished
After subscription

2. Essential Operators: map, filter, and tap

Definition

Operators are functions. There are two kinds:

  1. Creation Operators: Create a new Observable (e.g., of, from, interval).
  2. Pipeable Operators: Take an Observable as input and return a new Observable with modified behavior.

The Problem

Raw data from an API or event stream is rarely in the exact format the UI requires. We might receive a massive JSON object but only need one property, or we might receive null values that crash the application. Modifying this data inside the .subscribe() block leads to "callback hell" and untestable logic.

The Solution: The pipe() method

We use the .pipe() method to chain operators together. This allows us to transform data flow before it reaches the subscriber.

🔬 The Big Three

1. filter

Emits values only if they satisfy a predicate function.

  • Use case: Ignoring null values or user errors.

2. map

Applies a projection to each value emitted by the source.

  • Use case: Extracting specific data from an HTTP response or formatting strings.

3. tap

Used for side effects. It observes the data but does not modify it.

  • Use case: Logging, debugging, or triggering external void actions.

💻 Industry Practice: Data Transformation

Imagine we are fetching a list of users, but we only want active users, and we only need their names.

typescript
import { of } from 'rxjs'; // Creation operator
import { map, filter, tap } from 'rxjs/operators'; // Pipeable operators

interface User {
  id: number;
  name: string;
  isActive: boolean;
}

// Mock data source
const users: User[] = [
  { id: 1, name: 'Alice', isActive: true },
  { id: 2, name: 'Bob', isActive: false },
  { id: 3, name: 'Charlie', isActive: true },
];

// 'from' creates an observable from an array
import { from } from 'rxjs';

const userStream$ = from(users).pipe(
  // 1. TAP: Debug the raw input
  tap(user => console.log(`Processing: ${user.name}`)),

  // 2. FILTER: Only allow active users to pass
  filter(user => user.isActive === true),

  // 3. MAP: Transform the object to return only the name (uppercase)
  map(user => user.name.toUpperCase())
);

// Subscribe to the result
userStream$.subscribe(name => console.log(`Allowed: ${name}`));

Output:

text
Processing: Alice
Allowed: ALICE
Processing: Bob
Processing: Charlie
Allowed: CHARLIE

3. State Management Foundation: Subjects and BehaviorSubjects

Definition

A Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.

The Problem

  1. Unicast Nature: Standard Observables are "Cold." If you subscribe to an HTTP call Observable twice, it triggers the HTTP network request twice.
  2. Communication: How do unrelated components (e.g., a Sidebar and a Header) talk to each other?
  3. Late Subscription: If an event happens before a component subscribes, a standard Subject will not replay that event. The component misses the data.

The Solution: BehaviorSubject

A BehaviorSubject is a variant of Subject that requires an initial value and emits its current value to new subscribers immediately upon subscription.

💻 Industry Practice: The Service-Store Pattern

This is the most common pattern in Angular for managing state without external libraries like NgRx.

user.service.ts

typescript
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  // 1. Private BehaviorSubject: holds the value and write access.
  // Initial value is 'Guest'.
  private _currentUserSubject = new BehaviorSubject<string>('Guest');

  // 2. Public Observable: exposes read-only access to the rest of the app.
  // We use .asObservable() to prevent components from using .next() directly.
  public currentUser$: Observable<string> = this._currentUserSubject.asObservable();

  // 3. Method to update state
  login(username: string): void {
    console.log(`Logging in ${username}...`);
    this._currentUserSubject.next(username);
  }
}

Imagination Break 🧘

Imagine BehaviorSubject is a billboard. Even if you look at the billboard 5 minutes after the painter finished (late subscription), you still see the current image. A standard Subject is like a radio announcement; if you weren't listening at the exact moment it was said, you missed it forever.


4. Memory Management: Subscribing and Unsubscribing (Async Pipe)

Definition

Subscription Management is the process of initiating and cleaning up resources associated with an Observable execution.

The Problem: Memory Leaks

When you call .subscribe() in a component, a stream opens. If that component is destroyed (e.g., the user navigates to a different page) but the subscription is not closed, the stream remains active in the background.

  • This causes Memory Leaks.
  • It can lead to errors if the subscription tries to update a UI element that no longer exists.

The Solution: The AsyncPipe

Angular provides a built-in pipe called async. It subscribes to an Observable automatically in the template and, crucially, unsubscribes automatically when the component is destroyed.

🚫 The "Bad" Way (Manual Management)

typescript
// bad-example.component.ts
export class BadExampleComponent implements OnInit, OnDestroy {
  data: string;
  subscription: Subscription; // Requires importing Subscription

  constructor(private dataService: DataService) {}

  ngOnInit() {
    // ⚠️ Manual subscription
    this.subscription = this.dataService.data$.subscribe(val => {
      this.data = val;
    });
  }

  ngOnDestroy() {
    // ⚠️ Must remember to unsubscribe manually!
    // If you forget this, you create a memory leak.
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

✅ The "Good" Way (Async Pipe)

good-example.component.ts

typescript
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from './data.service';

@Component({
  selector: 'app-good-example',
  template: `
    <div *ngIf="data$ | async as data; else loading">
      <h1>User Data: {{ data }}</h1>
    </div>
    <ng-template #loading>Loading...</ng-template>
  `
})
export class GoodExampleComponent {
  // We don't subscribe here. We just assign the Observable.
  data$: Observable<string> = this.dataService.data$;

  constructor(private dataService: DataService) {}
}

Why this is better:

  1. Less Code: No ngOnInit or ngOnDestroy.
  2. Safety: Impossible to forget unsubscribing.
  3. Readability: Clearly indicates data is asynchronous.
  4. Change Detection: Works seamlessly with OnPush change detection strategies.

📚 Summary

  1. Observables are streams of events over time. Unlike Promises, they are lazy and can emit multiple values.
  2. Operators (map, filter, tap) allow us to transform data functionally inside a .pipe().
  3. BehaviorSubjects are used for State Management to hold a current value and share it with multiple subscribers.
  4. Async Pipe is the industry standard for consuming Observables in templates to prevent memory leaks.

🔗 References & Further Reading

Challenge

Challenge: Implement an RxJS-based User State Store

You are tasked with creating a simple state management store for an application's current user. Your goal is to process an incoming stream of raw user data, filter for an admin user, transform the data into a standardized format, and update a shared state using a BehaviorSubject.

Requirements:

  1. Define a BehaviorSubject named userState$ to hold the application's user state. Its initial value must represent a logged-out user with the following structure: { id: null, name: null, isLoggedIn: false, roles: [] }.
  2. You are provided with an Observable, rawUserData$, which emits a series of raw user objects.
  3. Create a new Observable by applying the .pipe() method to rawUserData$. This new stream must perform the following transformations in order:
    a. Filter: Only emit user objects where the roles array contains the string 'admin'.
    b. Map: Transform the filtered user object from its raw format ({ userId, username, roles }) to the standardized state format ({ id, name, isLoggedIn, roles }). Set isLoggedIn to true.
    c. Tap: For each emitted value from the map operator, perform a side-effect that logs the message "Admin user processed" to the console. This should not modify the stream's data.
  4. Subscribe to the fully transformed Observable and use the emitted value to update the userState$ BehaviorSubject by calling its .next() method.

Expected result

Your final code should correctly implement the user state store. The solution must include:

  1. A BehaviorSubject named userState$ initialized with { id: null, name: null, isLoggedIn: false, roles: [] }.
  2. A call to rawUserData$.pipe() containing three operators:
    • A filter operator that correctly identifies the user object with 'admin' in its roles array.
    • A map operator that transforms the filtered object into { id: 205, name: 'super_admin', isLoggedIn: true, roles: ['read', 'write', 'admin'] }.
    • A tap operator that is configured to log "Admin user processed".
  3. A .subscribe() call on the piped Observable.
  4. Inside the subscription, a call to userState$.next() which passes the transformed admin user object, updating the subject's value.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.