I am facing an issue with my user object in a membership service.
I need to ensure that my services are updated only when there are relevant changes in the user object.
To determine if there are relevant changes in the user object, I compare it with the local user object and then update it accordingly.
However, this process is not working as expected.
export class MemberService {
private subscription?: Subscription;
user?: User;
constructor(public auth: AuthService) {
this.subscription = this.auth.user$.subscribe((user) => {
const updateServices = this.hasUserRelevantChanges(user)
// It seems like this line always executes before the function call above?!
this.user = user;
if (updateServices) {
this.updateMyServices();
}
});
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
hasUserRelevantChanges(user: User | undefined): boolean {
return user?.subscription !== this.user?.subscription ||
user?.username !== this.user?.username ||
user?.isBanned !== this.user?.isBanned;
}
updateMyServices(): void {
// Updating my services!!!
}
}
export class AuthService {
public readonly user$: Observable<User| undefined> = this.user.asObservable();
user: BehaviorSubject<User| undefined> = new BehaviorSubject<User| undefined>(undefined);
constructor(private httpHandler: HttpHandlerService) { ... }
handleUser(): void {
this.httpHandler.login().subscribe(
(user: User) => this.user.next(user));
}
updateUserData(newUser: User): void {
this.user.next(Object.assign(this.user.value, newUser));
}
}
I'm confused why the function hasUserRelevantChanges()
keeps comparing the same new objects. The local this.user
already contains the new values within this check, even though the assignment this.user = user
comes afterwards?
How can I accurately determine if the new user
object has any relevant value changes compared to the old/previous user object?