I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed.
I've noticed that my current implementation doesn't seem to work correctly, and I suspect it's because of how I update the user object. It seems like I may be overwriting both the old and new values in the BehaviorSubject, resulting in always comparing the same object?
export interface User {
id: string;
username: string;
isBanned: boolean;
subscription?: UserSubscription;
}
export class AuthService {
public readonly user$: Observable<User| undefined> = this.user.asObservable();
user: BehaviorSubject<User| undefined> = new BehaviorSubject<User| undefined>(undefined);
updateUserSubscription(newUserSubscription: UserSubscription): void {
// Here I simply want to update the subscription-Object of my user
this.user.next(Object.assign(this.user.value, newUserSubscription));
}
}
export class MemberService {
user?: User;
private subscription?: Subscription;
constructor(public auth: AuthService) {
// Here I simply want to detect subscription changes
this.subscription = this.auth.user$.pipe(
pairwise(),
filter(users => this.detectSubscriptionChange(users[0], users[1]))
).subscribe(([user1, user2] => { // some code ... })
}
detectSubscriptionChange(user1: User | undefined, user2: User | undefined): boolean {
//subscription status is always the same, as the objects are always the same...
return user1?.subscription?.status !== user2?.subscription?.status;
}
}
Is there a better way for me to update the values in my user object so that I can accurately compare them in the observable?
Thank you!