Will overwriting my observable variable kill current subscribers?

会有一股神秘感。 提交于 2021-02-19 03:05:55

问题


I want to be able to cache an http call, but also force the cache to refresh. My service looks like this:

@Injectable()
export class UserService {
  private currentUser$: Observable<User>;

  constructor(private http: HttpClient) { }

  getCurrentUser(force = false): Observable<User> {
    if (!this.currentUser$ || force) {
      this.currentUser$ = this.http.get<User>(`${environment.API_URL}/profiles/me`)
        .pipe(
          shareReplay(CACHE_SIZE)
        );
    }
    return this.currentUser$;
  }
}

If I call getCurrentUser(true), the currentUser$ variable gets overwritten. I'm afraid this will wipe out any existing subscribers. Is this true? How can I preserve them?


回答1:


Think about this.currentUser$ as pointing to an object on the heap. Your method returns a copy of the reference to this.currentUser$. So all subscribed observers will continue to listen to them (until all of them unsubscribe and the Observable gets garbage collected).

If you call the method with "force", the this.currentUser$ will just point to another Observable<User> somewhere else on the heap.




回答2:


I'm going to post what I did here in case it helps anyone else. I return a single instance of BehaviorSubject instead and just push new values to it whenever I need to "force" getting the current user. I also added a flag fetchingCurrentUser so that I don't make multiple calls while I'm waiting for the first call to the API to complete.

Please let me know if anyone sees any issues with this or has any ideas on how to make it cleaner. Thanks.

@Injectable()
export class UserService {
  private currentUser$: BehaviorSubject<User>;
  private fetchingCurrentUser: boolean;

  constructor(private http: HttpClient) {
    this.currentUser$ = new BehaviorSubject(null);
  }

  getCurrentUser(force = false): Observable<User> {
    if (this.currentUser$.value == null || force) {
      this.refreshCurrentUser();
    }
    return this.currentUser$.asObservable();
  }

  refreshCurrentUser() {
    if (!this.fetchingCurrentUser) {
      this.fetchingCurrentUser = true;
      this.http.get<User>(`${environment.API_URL}/profiles/me`)
        .subscribe(x => {
          this.currentUser$.next(x);
          this.fetchingCurrentUser = false;
        });
    }
  }


来源:https://stackoverflow.com/questions/52526166/will-overwriting-my-observable-variable-kill-current-subscribers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!