需要退订 Firestore/Angularfire2 个订阅

Need to unsubscribe Firestore/Angularfire2 subscription

我是这样用 Firestore 的。

用例 1:

contacts$: Observable<ContactDetail[]>;

constructor(){    
} 

ionViewDidEnter() {
   this.contacts$ = this.contactProvider.getSpecificUserContacts(this.authenticationProvider.user.uid).valueChanges();
   this.contacts$.pipe(first()).subscribe(res => { },
      err => { },
      () => { }
   );
}

用例 2:

getAllContactCategories() {
    this.categories$ = this.categoryProvider.getAllContactCategories().valueChanges();
    this.categories$.subscribe(res => {
       this.categorySortedList = res;          
    },
      err => { }
    );
}

但我从来没有unsubscribed。那我需要这样做吗?否则,会不会导致内存泄漏和电池耗尽? 我知道我们不需要 unsubscribed angular HTTP 服务,因为它由框架本身自动完成。那么 Firestore/Angularfire2 observables 呢?我从未在 firestore 书籍或文章中看到过这样的模式。

通过使用 first() 运算符,您将在最初触发订阅后直接自动取消订阅。但是要回答你的具体问题。

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed. There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions. The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Feel free to unsubscribe anyway. It is harmless and never a bad practice.

来自https://angular.io/guide/route

一般来说,如果您想控制何时取消订阅,您可以将可观察对象分配给一个变量

const subscription = this.subscription$.valueChanges().subscribe(...);

然后在新创建的变量上调用取消订阅。

subscription.unsubscribe();

是的,订阅的退订就好了。你可以试试这个...

  contactsSub: Subscription;

构造函数(){
}

ionViewDidEnter() { ... }

  ionViewDidLeave{
  this.contactsSub.unsubscribe();
  }

来自 angularfire2 代表: https://github.com/angular/angularfire2/issues/377