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!
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
.2. Create a boolean to limit when the subscription runs.
Use
ionViewDidLeave
forIonicPage
components andngOnDestroy
for custom components.If you want data to persist while the device is offline, you should look into ngrx/store.