取消订阅 observables 的 Ionic & AngularFire2 最佳实践

Ionic & AngularFire2 best practice for unsubscribing to observables

我有一个使用 AngularFire2 和 Firestore 的多页 Ionic-Angular phone 应用程序。我真正喜欢 Firestore 的一件事是数据的离线持久性。我的问题围绕着这种数据持久性和取消订阅 AngularFire2 流可观察量的最佳实践。

My home page is a list of events and when an event is selected the app routes to a single-event page with this specific event's details.目前,我根据单事件组件 ngOnInit 中 Firestore 中所选事件的文档 ID,使用 AngularFire2 API 订阅了单事件。

我对 Angular 中的 observables 的理解是,建议在退出组件时取消订阅 observables。但是,如果我在单事件组件中执行此操作并且用户以某种方式失去了互联网连接,当他们导航到主页然后返回到单事件时,没有数据,因为流可观察对象已取消订阅并且应用程序无法联系 Firestore。现在如果我不退订,那么即使离线,单事件页面仍然显示数据。这是我想要的行为,但是我在离开单事件页面时没有取消订阅可观察对象是否有某种问题?

即使在基于 Ionic 的 phone 应用程序中,取消订阅 observables 也很重要吗?还是我应该重新设计我的应用程序以实现所有最佳实践? 感谢您的任何投入!

Is it important to unsubscribe to observables even in an Ionic based phone app?

是的,否则如果您离开该页面并返回,它会创建另一个对同一个可观察对象的订阅,这会导致内存泄漏。

我知道有几种方法可以在您离开时停止订阅。
1. 创建、分配和取消订阅 Subscription.

foo$: Observable<Foo>;
fooSub: Subscription;

constructor() {
  this.fooSub = this.foo$.subscribe(foo => { console.log(foo); });
}

ionViewDidLeave() {
  this.fooSub.unsubscribe();
}

2。创建一个布尔值来限制订阅运行的时间。

active: boolean = true;
foo$: Observable<Foo>;

constructor() {
  this.foo$.takeWhile(() => this.active).subscribe(foo => { console.log(foo); });
}

ionViewDidLeave() {
  this.active = false;
}

ionViewDidLeave 用于 IonicPage 组件,ngOnDestroy 用于自定义组件。

如果您希望数据在设备离线时持续存在,您应该查看 ngrx/store