javascript / intermediate
Snippet
State Management with BehaviorSubject
A BehaviorSubject is a specialized Subject that requires an initial value and emits the current value to new subscribers immediately. It is a lightweight pattern for managing and sharing application state across services.
snippet.js
1
2
3
4
5
6
7
8
9
10
private userState = new BehaviorSubject<User | null>(null);user$ = this.userState.asObservable();updateUser(newUser: User) {this.userState.next(newUser);}getCurrentUser() {return this.userState.value;}
angular
Breakdown
1
new BehaviorSubject<User | null>(null)
Initializes the state with 'null' as the starting value.
2
this.userState.next(newUser)
Updates the state and notifies all current observers of the new data.