Ionic & AngularFire2 best practice for unsubscribing to observables

旧巷老猫 提交于 2019-12-24 09:01:24

问题


I have a multi-page Ionic-Angular phone app that uses AngularFire2 & Firestore. One of the things I really like about Firestore is offline persistence of data. My question revolves around this data persistence and best practices for unsubscribing to AngularFire2 stream observables.

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. Currently I subscribe to the single-event using AngularFire2 API based on the selected event's doc ID in Firestore within the single-event component ngOnInit.

My understanding of observables in Angular is that it is recommended to unsubscribe to observables when navigating back out of a component. However, if I do this in the single-event component and the user somehow loses internet connectivity, when they navigate to home page and then back to a single-event, there is no data since the stream observables have been unsubscribed and the app cannot contact Firestore. Now if I do not unsubscribe, then the single-event page still displays data even if offline. This is the behavior that I want, but is it a problem somehow that I am not unsubscribing to observables when leaving single-event page?

Is it important to unsubscribe to observables even in an Ionic based phone app? Or should I be re-architecting my app to achieve all best practices? Thanks for any inputs!


回答1:


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

Yes, otherwise if you were to leave the page and come back it would create another subscription to the same observable which would cause memory leaks.

There are a couple ways that I know of to stop subscriptions when you nav away.
1. Create, assign and unsubscribe from a Subscription.

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

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

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

2. Create a boolean to limit when the subscription runs.

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

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

ionViewDidLeave() {
  this.active = false;
}

Use ionViewDidLeave for IonicPage components and ngOnDestroy for custom components.

If you want data to persist while the device is offline, you should look into ngrx/store.



来源:https://stackoverflow.com/questions/50976777/ionic-angularfire2-best-practice-for-unsubscribing-to-observables

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