A BehaviorSubject lets you keep and share a value that changes over time. It works like a simple store to hold and update data in Angular apps.
0
0
BehaviorSubject as simple store in Angular
Introduction
You want to share data between different components without complex setup.
You need to keep the latest value available for new subscribers immediately.
You want a simple way to update and listen to data changes reactively.
You want to avoid using heavy state management libraries for small apps.
Syntax
Angular
import { BehaviorSubject } from 'rxjs'; const store = new BehaviorSubject(initialValue); // To get current value const currentValue = store.getValue(); // To update value store.next(newValue); // To listen for changes store.subscribe(value => { // react to value });
The BehaviorSubject always holds the latest value.
Subscribers get the current value right away when they subscribe.
Examples
This example creates a store holding a number. It logs the count whenever it changes.
Angular
const countStore = new BehaviorSubject(0); countStore.subscribe(value => console.log('Count:', value)); countStore.next(1); countStore.next(2);
Here the store holds an object representing user info. We update the login status.
Angular
const userStore = new BehaviorSubject({ name: 'Alice', loggedIn: false }); userStore.next({ name: 'Alice', loggedIn: true });
Sample Program
This Angular component uses a BehaviorSubject as a simple store to keep user info. It shows the user's name and login status. Clicking the button toggles the login state. The component updates automatically when the store changes.
Angular
import { Component } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Component({ selector: 'app-simple-store', template: ` <h2>User Status</h2> <p>Name: {{ user.name }}</p> <p>Status: {{ user.loggedIn ? 'Logged In' : 'Logged Out' }}</p> <button (click)="toggleLogin()">Toggle Login</button> ` }) export class SimpleStoreComponent { private userStore = new BehaviorSubject({ name: 'Alice', loggedIn: false }); user = this.userStore.value; constructor() { this.userStore.subscribe(value => { this.user = value; }); } toggleLogin() { const current = this.userStore.value; this.userStore.next({ ...current, loggedIn: !current.loggedIn }); } }
OutputSuccess
Important Notes
Always unsubscribe from subscriptions in real apps to avoid memory leaks (not shown here for simplicity).
BehaviorSubject requires an initial value when created.
Summary
BehaviorSubject holds and shares the latest value like a simple store.
Subscribers get the current value immediately when they subscribe.
Use next() to update the store value and notify subscribers.