Angular RxJS Basics

Learn Angular RxJS Basics with Observables, Observers, Subscriptions, Operators, Subjects, Async Pipe, architecture diagrams, enterprise examples, best practices, and interview questions.

RxJS (Reactive Extensions for JavaScript) is a powerful library for reactive programming using Observables.

Angular is built around RxJS. Many Angular features internally use Observables, including:

  • HttpClient
  • Router
  • Forms
  • Event Handling
  • WebSockets
  • Signals Interoperability
  • State Management

Understanding RxJS is essential for building scalable, responsive, and maintainable Angular applications.

RxJS Basics is one of the most frequently asked Angular interview topics.


Table of Contents

  • What is RxJS?
  • Why Use RxJS?
  • Reactive Programming
  • Observable
  • Observer
  • Subscription
  • Observable Lifecycle
  • Creating Observables
  • Operators
  • Async Pipe
  • Subjects
  • Enterprise Banking Example
  • Performance Best Practices
  • Common Mistakes
  • Top 10 Interview Questions
  • Summary

What is RxJS?

RxJS is a library that enables reactive programming using Observables.

Instead of waiting for data synchronously, an application reacts whenever new data becomes available.

Examples

  • HTTP Responses
  • Mouse Clicks
  • Keyboard Events
  • Timers
  • WebSocket Messages
  • Form Value Changes

Reactive Programming

Reactive programming is a programming paradigm where applications react to streams of asynchronous events instead of polling or blocking.

Traditional Flow

Request

↓

Wait

↓

Response

Reactive Flow

Event

↓

Observable

↓

Subscriber

↓

Reaction

RxJS Architecture

flowchart LR

Source

Source --> Observable

Observable --> Operator

Operator --> Subscriber

Subscriber --> UI

Why Use RxJS?

Without RxJS

  • Callback nesting
  • Complex async code
  • Difficult error handling
  • Hard to combine asynchronous operations

With RxJS

  • Clean asynchronous programming
  • Powerful operators
  • Better composition
  • Easier error handling
  • Stream processing

What is an Observable?

An Observable is a data producer that emits values over time.

An Observable can emit:

  • One value
  • Multiple values
  • No values
  • An error
  • A completion notification

Examples

  • HTTP Requests
  • Route Parameters
  • Form Changes
  • Timer Events
  • WebSockets

Observable Architecture

flowchart TD

Observable

Observable --> Next

Observable --> Error

Observable --> Complete

Creating an Observable

import { Observable } from 'rxjs';

const numbers$ = new Observable<number>(observer => {

  observer.next(10);

  observer.next(20);

  observer.next(30);

  observer.complete();

});

The Observable emits three values and then completes.


What is an Observer?

An Observer consumes values emitted by an Observable.

It can respond to three notifications:

  • next
  • error
  • complete

Example

numbers$.subscribe({

  next: value => {

    console.log(value);

  },

  error: err => {

    console.error(err);

  },

  complete: () => {

    console.log('Completed');

  }

});

Observable Lifecycle

sequenceDiagram

participant Observable

participant Observer

Observable->>Observer: next()

Observable->>Observer: next()

Observable->>Observer: next()

Observable->>Observer: complete()

What is a Subscription?

Calling subscribe() starts the Observable execution and returns a Subscription.

const subscription =

numbers$

.subscribe(value => {

console.log(value);

});

To stop receiving values:

subscription.unsubscribe();

Unsubscribing helps prevent memory leaks for Observables that continue emitting values.


Subscription Architecture

flowchart LR

Observable

Observable --> Subscription

Subscription --> Observer

Observer --> UI

Cold vs Hot Observables

Cold Observable Hot Observable
Starts producing values for each subscriber Shares an existing stream among subscribers
HTTP requests are common examples Subjects are common examples
Each subscriber gets its own execution Subscribers share emissions

Example

Cold Observable

Subscriber A

↓

New HTTP Request

Subscriber B

↓

Another HTTP Request

Hot Observable Architecture

flowchart TD

Subject

Subject --> ComponentA

Subject --> ComponentB

Subject --> ComponentC

RxJS Operators

Operators transform, filter, or combine Observable streams.

Common Operators

Operator Purpose
map Transform values
filter Filter values
tap Side effects
switchMap Switch to a new Observable
mergeMap Merge inner Observables
concatMap Execute sequentially
catchError Handle errors
retry Retry failed streams
debounceTime Delay rapid events
distinctUntilChanged Ignore duplicate consecutive values

Example

import {

map

} from 'rxjs/operators';

numbers$

.pipe(

map(

value => value * 2

)

)

.subscribe(

console.log

);

Operator Flow

flowchart LR

Observable

Observable --> map

map --> filter

filter --> Subscriber

Async Pipe

Angular's Async Pipe subscribes to an Observable and automatically unsubscribes when the view is destroyed.

Component

users$ =

this.userService

.getUsers();

Template

<ul>

<li *ngFor="let user of users$ | async">

{{ user.name }}

</li>

</ul>

Benefits

  • Automatic subscription management
  • Cleaner templates
  • Reduced memory leaks

Async Pipe Architecture

flowchart TD

Observable

Observable --> AsyncPipe

AsyncPipe --> Template

Template --> UI

Subjects

A Subject is both an Observable and an Observer.

It can:

  • Receive values
  • Emit values
  • Broadcast values to multiple subscribers

Example

import {

Subject

} from 'rxjs';

const subject =

new Subject<number>();

subject.subscribe(

value =>

console.log(

'A',

value

)

);

subject.subscribe(

value =>

console.log(

'B',

value

)

);

subject.next(100);

Output

A 100

B 100

Subject Architecture

flowchart LR

Subject

Subject --> ComponentA

Subject --> ComponentB

Subject --> ComponentC

Observable vs Promise

Observable Promise
Multiple values Single value
Lazy execution Eager execution
Cancelable via Subscription Cannot be canceled directly
Many RxJS operators Limited chaining
Used throughout Angular Used in JavaScript

Enterprise Banking Example

Online Banking Dashboard

Observable Streams

  • Account Balance
  • Transactions
  • Notifications
  • Stock Prices
  • Payment Status
  • Chat Messages

Architecture

flowchart TD

AngularApp

AngularApp --> BankingService

BankingService --> HttpClient

HttpClient --> BankingAPI

BankingAPI --> Observable

Observable --> Components

Benefits

  • Real-time updates
  • Better responsiveness
  • Reduced polling
  • Scalable architecture
  • Cleaner asynchronous code

RxJS Data Flow

flowchart LR

DataSource

DataSource --> Observable

Observable --> Operators

Operators --> Subscriber

Subscriber --> UI

Performance Best Practices

Practice Benefit
Prefer Async Pipe in templates Automatic cleanup
Unsubscribe from long-lived Observables Prevent memory leaks
Use RxJS operators instead of nested subscriptions Cleaner code
Use switchMap() for request cancellation Better UX
Keep Observable chains readable Easier maintenance
Share streams when appropriate Avoid duplicate work

Common Mistakes

Nested Subscriptions

Avoid

service1.get()

.subscribe(a => {

service2.get()

.subscribe(b => {

});

});

Prefer operators like switchMap() or concatMap().


Forgetting to Unsubscribe

Long-lived subscriptions can cause memory leaks.

Use:

  • Async Pipe
  • takeUntil()
  • Angular lifecycle-aware utilities when appropriate

Using Subject Everywhere

Use a Subject only when you need multicasting or manual event emission.

For simple HTTP requests, return the Observable from HttpClient.


Ignoring Error Handling

Always handle errors using:

  • catchError()
  • error callback in subscribe()
  • HTTP Interceptors (for HTTP concerns)

Overusing Operators

Keep Observable pipelines readable and focused.


Best Practices

  • Prefer Observables for asynchronous workflows.
  • Use Async Pipe in templates.
  • Keep Observable chains simple.
  • Handle errors consistently.
  • Avoid nested subscriptions.
  • Use Subjects only when needed.
  • Unsubscribe from long-lived streams.
  • Use appropriate mapping operators.
  • Write unit tests for Observable logic.
  • Follow reactive programming principles.

Advantages

Feature Benefit
Observable Asynchronous data streams
Operators Powerful stream transformations
Async Pipe Automatic subscription management
Subject Multicasting
Error Handling Reliable applications
Enterprise Ready Scalable architecture

Top 10 Angular RxJS Basics Interview Questions

1. What is RxJS?

Answer

RxJS is a library for reactive programming using Observables to process asynchronous and event-based data streams.


2. What is an Observable?

Answer

An Observable is a data source that emits values over time and can emit data, errors, or completion notifications.


3. What is an Observer?

Answer

An Observer subscribes to an Observable and handles next, error, and complete notifications.


4. What is a Subscription?

Answer

A Subscription represents the execution of an Observable and allows you to cancel it using unsubscribe().


5. What are RxJS Operators?

Answer

Operators transform, filter, combine, or control Observable streams. Examples include map, filter, switchMap, catchError, and retry.


6. What is the Async Pipe?

Answer

The Async Pipe automatically subscribes to an Observable, updates the template with emitted values, and unsubscribes when the component is destroyed.


7. What is a Subject?

Answer

A Subject is both an Observable and an Observer, allowing values to be multicasted to multiple subscribers.


8. What is the difference between a Cold and Hot Observable?

Answer

Cold Observables create a new execution for each subscriber, while Hot Observables share the same execution among multiple subscribers.


9. Observable vs Promise?

Answer

Observables can emit multiple values, are lazy, cancelable through subscriptions, and provide many operators. Promises resolve only once and execute eagerly.


10. What are RxJS best practices?

Answer

  • Prefer Async Pipe.
  • Avoid nested subscriptions.
  • Handle errors with catchError().
  • Unsubscribe from long-lived Observables.
  • Use Subjects only when needed.
  • Keep Observable chains readable.

Interview Cheat Sheet

Topic Remember
Reactive Library RxJS
Data Source Observable
Data Consumer Observer
Start Execution subscribe()
Cancel unsubscribe()
Transform Data map()
Error Handling catchError()
Automatic Subscription Async Pipe
Multicasting Subject
Best Practice Avoid nested subscriptions

Summary

RxJS is the foundation of Angular's reactive programming model. By using Observables, Observers, Subscriptions, Operators, Async Pipe, and Subjects, developers can efficiently manage asynchronous data, build responsive user interfaces, and create scalable enterprise applications. Understanding these fundamentals is essential before exploring advanced RxJS concepts such as higher-order mapping operators, multicasting, schedulers, and state management.


Key Takeaways

  • ✔ RxJS powers Angular's asynchronous programming model.
  • ✔ Observables emit values over time.
  • ✔ Observers consume emitted values.
  • ✔ Subscriptions start Observable execution.
  • ✔ Operators transform and manage data streams.
  • ✔ Async Pipe automatically manages subscriptions.
  • ✔ Subjects support multicasting.
  • ✔ Prefer reactive operators over nested subscriptions.
  • ✔ Unsubscribe from long-lived streams to avoid memory leaks.
  • ✔ RxJS Basics is one of the most important Angular interview topics.

Next Article

➡️ 71-RxJS-Operators-QA.md