Observables & Observers in RxJS

RxJS Observables & Observers in Angular – Complete Guide

๐Ÿš€ Observables & Observers in RxJS – Complete Angular Guide

๐Ÿ“˜ Introduction

RxJS (Reactive Extensions for JavaScript) is a powerful library used in Angular for reactive programming. It enables handling asynchronous data streams using Observables, a pattern that allows multiple emissions over time.

In Angular, Observables are commonly used with:

  • HttpClient for API calls
  • Reactive Forms (FormControl.valueChanges)
  • Routing events and user interactions

๐Ÿ” What Are Observables?

An Observable is a data stream that can emit multiple values over time. It follows the Observer pattern, where an Observer subscribes to listen for values, errors, or completion signals from the Observable.

⚙️ Creating Observables in RxJS

๐Ÿ’ป Basic Observable Example

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  observer.next('Hello');
  observer.next('RxJS');
  observer.complete();
});

observable.subscribe(value => console.log(value));
  • observer.next(value): Emits a value.
  • observer.complete(): Signals the end of the stream.
  • observer.error(err): Emits an error and stops the stream.
Tip: Always handle observer.error() in your subscriptions to prevent uncaught exceptions.

⚠️ Error Handling Example

const errorObservable = new Observable(observer => {
  observer.next('Before error');
  observer.error('Something went wrong');
});

errorObservable.subscribe({
  next: val => console.log(val),
  error: err => console.error('Caught Error:', err),
  complete: () => console.log('Completed')
});

๐Ÿ”„ Subscribing & Unsubscribing

To receive values from an Observable, you subscribe to it. In Angular components, you must unsubscribe when the component is destroyed to prevent memory leaks.

✅ Subscribing Example

const observable = new Observable(observer => {
  observer.next('First Value');
  setTimeout(() => observer.next('Second Value'), 2000);
  setTimeout(() => observer.complete(), 3000);
});

const subscription = observable.subscribe({
  next: value => console.log('Received:', value),
  complete: () => console.log('Observable Completed'),
});

๐Ÿงน Unsubscribing Example (Angular)

import { Component, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-example',
  template: `

Check the console

` }) export class ExampleComponent implements OnDestroy { private subscription: Subscription; constructor() { const observable = new Observable(observer => { setInterval(() => observer.next('Emitted Value'), 1000); }); this.subscription = observable.subscribe(value => console.log(value)); } ngOnDestroy() { this.subscription.unsubscribe(); console.log('Unsubscribed'); } }
Gotcha: If you forget to unsubscribe, your component may keep running after destruction—leading to unexpected behavior and memory leaks.

๐Ÿ“Š Observables vs Promises

While Promises handle a single asynchronous value, Observables provide greater flexibility and control over asynchronous data streams.

Feature Observables Promises
Lazy Execution✅ Yes❌ No
Multiple Values✅ Yes❌ No
Cancellation✅ Yes (unsubscribe)❌ No
Operators✅ map, filter, debounceTime, switchMap❌ Not available
Error Handling✅ Can recover and continue❌ Ends execution

๐Ÿ“˜ Promise Example

const promise = new Promise(resolve => {
  setTimeout(() => resolve('Promise Resolved'), 2000);
});

promise.then(value => console.log(value));

๐Ÿ“˜ Observable Example

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  observer.next('Observable Emitted');
  setTimeout(() => observer.next('Observable Emitted Again'), 2000);
});

observable.subscribe(value => console.log(value));

Conclusion

  • Observables offer more flexibility than Promises.
  • They're essential for Angular features like HTTP, forms, and events.
  • Always unsubscribe to prevent memory leaks in Angular components.
Tip: Prefer the async pipe in Angular templates to automatically manage subscriptions.

๐Ÿ“– Next Topics: Explore Subject vs BehaviorSubject along with switchMap to master reactive patterns in Angular.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features