I have a user object which I observe in a membership service.
I want to update my services only if the user object has relevant changes.
To understand if my user object has relevant changes, I compare my local user object with the observed one. And always assign the new object afterwards.
This does not work, however.
export class MemberService {
private subscription?: Subscription;
user?: User;
constructor(public auth: AuthService) {
this.subscription = this.auth.user$.subscribe((user) => {
const updateServices = this.hasUserRelevantChanges(user)
// apparently this line always fires before the functioncall 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));
}
}
How come that my function hasUserRelevantChanges()
always compares the same, new objects? The local this.user
always holds the new values already within this check, eventhough the assignment this.user = user
comes afterwards?
So how can I understand if my new user
object has the relevant values changed in comparison to the old/previous user-object?