0
0
Angularframework~3 mins

Why BehaviorSubject as simple store in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple tool can save you from endless manual updates and bugs!

The Scenario

Imagine you have a shopping cart in your app. Every time a user adds or removes an item, you manually update the cart display in many places.

You have to write code to notify each part of your app about the change.

The Problem

Manually tracking and updating all parts of your app is tiring and error-prone.

You might forget to update some views, causing inconsistent data shown to users.

This leads to bugs and a poor user experience.

The Solution

Using BehaviorSubject as a simple store lets you keep the cart data in one place.

When the cart changes, BehaviorSubject automatically notifies all parts of your app that care.

This keeps your app data consistent and your code clean.

Before vs After
Before
let cart = [];
function addItem(item) {
  cart.push(item);
  updateCartDisplay();
  updateCartSummary();
}
After
import { BehaviorSubject } from 'rxjs';
const cart$ = new BehaviorSubject([]);
function addItem(item) {
  cart$.next([...cart$.value, item]);
}
cart$.subscribe(updateCartDisplay);
cart$.subscribe(updateCartSummary);
What It Enables

You can build apps where data flows smoothly and updates everywhere instantly without messy manual code.

Real Life Example

Think of a live chat app where new messages appear automatically for all users without refreshing the page.

BehaviorSubject helps keep the message list updated everywhere.

Key Takeaways

Manual updates are slow and error-prone.

BehaviorSubject keeps shared data in one place.

It automatically notifies all parts of your app when data changes.