I'm currently experiencing a bit of trouble trying to update a cached value using publishReplay and refCount.
First off, the method in question
getCurrentUser(): Observable<User> {
if (!this.jwtService.getToken() || this.jwtService.getAnonymousToken()) { return of(null); }
if (!this.currentUser$) {
console.warn('user.service.getcurrentuser -> load and CACHE it once');
this.currentUser$ = this.userService.loadCurrentUser().pipe(
// https://medium.com/angular-in-depth/fastest-way-to-cache-for-lazy-developers-angular-with-rxjs-444a198ed6a6
publishReplay(1),
refCount()
);
}
console.log('user.service.getcurrentuser -> get from CACHE');
return this.currentUser$;
}
this.currentUser$ is an Observable of type User.
The method itself works as intended, the first call of the method loads the current user from the server. Subsequent calls then get the cached entry. What I'm trying to do now, however, is to remove the cached value and reload the user from the server (ie. something was edited on the frontend and the user data requires reloading).
That I achieved by doing
removeCachedUser(): void {
this.currentUser$ = null;
}
By doing this the if condition in the getCurrentUser method is triggered and the user is reloaded from the server. So far, so good.
The problem I'm facing is that methods that subscribed to getCurrentUser before the reset of the cache aren't receiving any updates, ie
ngOnInit() {
this.currentUser$ = this.authService.getCurrentUser();
}
And my suspicion is that it's because of my overwriting the this.currentUser$ Observable.
this.currentUser$ = this.userService.loadCurrentUser()
This post more or less confirms my theory I suppose.
Am I right? And if so, what's the proper way to handle this issue? Unfortunately, I don't have a reactive backend so I have to trigger the reloads manually. Thanks in advance!