Feb 19, 2025

What Are Observables? A Beginner-Friendly Guide with Examples

Tags

Have you ever dealt with API calls, event listeners, or real-time updates in JavaScript? Handling asynchronous data can get tricky, but Observables make it easy! In this post, I'll explain Observables using a simple real-world analogy, break down how they work, and show some easy code examples!


Real-Life Analogy

📌 Think of Observables Like a Newspaper Subscription

  • You subscribe to a newspaper (Observer subscribes).
  • Every time a new edition is published, it gets delivered to your house (Observable emits data).
  • You keep receiving newspapers until you unsubscribe (Observable completes).
obseravables

How Observables Work

Observables emit values over time, and we can subscribe to listen for updates.

Basic Example: Creating an Observable
👉 The observable sends values, and the subscriber listens to them.
👉 next() → Emits a value
👉 complete() → Signals the end of the stream


When Should You Use Observables?

Observables are great for:
Real-time updates (WebSockets, live notifications)
Handling API calls efficiently (chained requests, retries)
User interactions (search autocomplete, click events)


Observables vs Promises

Feature Observables Promises
Emits multiple values ✅ Yes ❌ No (only once)
Supports operators (map, filter, etc.) ✅ Yes ❌ No
Can be cancelled ✅ Yes (unsubscribe) ❌ No
Lazy execution ✅ Yes ❌ No (executes immediately)

👉 Have you used Observables before? What was your experience like? Let’s discuss in the comments!



EmoticonEmoticon