Let's consider a scenario where we have a BehaviorSubject containing a User interface:
interface User {
firstName: string;
lastName: string;
}
let user: User = {
firstName: 'Cuong',
lastName: 'Le',
};
let bs = new BehaviorSubject<User>(user);
There are two subscriptions in play here. sub1
attempts to modify the first name, while sub2
subscribes later and sees the updated first name from the changes made by sub1
:
let sub1 = bs.subscribe((u) => {
u.firstName = 'An';
console.log(u);
});
let sub2 = bs.subscribe((u) => {
console.log(u);
});
In larger Angular applications, debugging becomes a challenge when such scenarios arise. How can we ensure immutability of values when subscribing?
I'm interested in exploring deeply immutable solutions to prevent any external code from altering the data unintentionally.