覆盖我的可观察变量会杀死当前订阅者吗? [英] Will overwriting my observable variable kill current subscribers?

查看:79
本文介绍了覆盖我的可观察变量会杀死当前订阅者吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够缓存http调用,但也可以强制刷新刷新.我的服务如下:

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$;
  }
}

如果我调用 getCurrentUser(true),则 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?

推荐答案

考虑 this.currentUser $ 指向堆上的对象.您的方法返回对 this.currentUser $ 的引用的副本.因此,所有订阅的观察者将继续收听(直到他们全部取消订阅并且Observable获得垃圾回收).

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).

如果使用"force"调用该方法,则 this.currentUser $ 只会指向堆上其他位置的另一个 Observable< User> .

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

这篇关于覆盖我的可观察变量会杀死当前订阅者吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆