Tool for HR, Hiring Managers, and the Leadership Team

What are Observables in Angular?

In Angular, Observables are a core concept used for handling asynchronous data streams. They come from the RxJS library, which Angular heavily relies on.

What is an Observable?

An Observable is a stream of data that can emit multiple values over time (unlike Promises, which emit only once).

Think of it like:

  • A YouTube live stream → continuous data

  • A button click event → emits values when user clicks

  • An HTTP call → emits response when data arrives

Key Characteristics

  • Lazy → Doesn’t execute until subscribed

  • Can emit multiple values → 0, 1, or many

  • Supports async operations → HTTP calls, events, timers

  • Can be cancelled → using unsubscribe

Basic Syntax

import { Observable } from 'rxjs';

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

Subscribing:

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

Where Observables are used in Angular

  1. HTTP Calls

this.http.get('/api/data')  // returns Observable
  1. Reactive Forms

this.form.valueChanges.subscribe()
  1. Routing

this.route.params.subscribe()
  1. Event Handling

fromEvent(button, 'click')

Observable vs Promise (Important Interview Question)

Feature Observable Promise
Values Multiple Single
Execution Lazy Eager
Cancelable Yes No
Operators Rich (map, filter, etc.) Limited
Streams Yes No

Operators (Very Important)

Operators help transform and manipulate data streams.

Examples:

import { map, filter } from 'rxjs/operators';

this.http.get('/api/users')
  .pipe(
    filter(users => users.length > 0),
    map(users => users[0])
  )
  .subscribe(data => console.log(data));

Types of Observables

  1. Cold Observable

    • Starts execution on subscription

    • Example: HTTP request

  2. Hot Observable

    • Already producing values (like events)

    • Example: mouse clicks

Unsubscribing (Important for memory leaks)

subscription.unsubscribe();

OR using Angular best practice:

takeUntil(this.destroy$)

Subject (Advanced Interview Topic)

A Subject is both:

  • Observable (can be subscribed)

  • Observer (can emit values)

const subject = new Subject();
subject.next('Hello');
subject.subscribe(val => console.log(val));

Types:

  • Subject

  • BehaviorSubject

  • ReplaySubject

Real-Life Angular Example

this.http.get('/api/users')
  .subscribe(users => {
    this.users = users;
  });

Common Interview Questions

  • What is the difference between Observable and Promise?

  • Why Angular uses Observables instead of Promises?

  • What are operators?

  • What is Subject vs Observable?

  • How do you prevent memory leaks?

One-Line Summary

Observable = A lazy, cancellable stream of multiple asynchronous values over time.