2

My goal is to subscribe to snapshotChanges() of a firestore collection when entering a view and unsubscribing from that when leaving the view.

Problem: The subscription works fine, unsubscribing does not work.

I followed the answer in this angularfire git thread.

Here is part of my code:

subscriptions: any[] = [];

ionViewWillEnter() {
  console.log('View will enter...');
  this.subscriptions.push(
    this.firestore.collection('/somecollection/').snapshotChanges().subscribe(docs => {
    // Functions that use docs and
    // more subscriptions of the same type nested in here
    console.log('Subscription #', someUniqueSubIdentifier);
    })
  );
}

goToOtherPage() {
  this.router.navigate(['/some-other-page']);
}

ionViewWillLeave() {
  console.log('View will leave...');
  for (const sub of this.subscriptions) {
    sub.unsubscribe();
  }
  console.log('All subscriptions: ', this.subscriptions);
}

The problem is that the subscription doesn't work here. I get the following prints after leaving the view for the first time and coming back to it.

View will enter...
Subscription #1 //(once and for every occurring change as expected)
View will leave...
All subscriptions:  (3) [Subscriber, Subscriber, Subscriber]
// (User pushed changes to the collection in the meantime)
View will enter...
Subscription #1 (not expected)
Subscription #2 (expected)

Can anybody help? Why does unsubscribe() not work here?

My ionic and angular versions:

Ionic CLI: 6.12.1

Ionic Framework: @ionic/angular 5.3.4

"@angular/fire": "^6.0.4"

Gabriel309
  • 36
  • 3
  • It looks as though you are leaving the page, but then entering another one of the same type which is logging the new subscriptions. Can you share the code of you leaving the page/navigating to the new page? – mahi-man Nov 02 '20 at 00:15
  • @mahi-man I added it to the question, thanks in advance. What do you mean by logging? – Gabriel309 Nov 02 '20 at 13:14
  • Are you sure that `this.subscriptions` is filled on `ionViewWillLeave`? Can you log it or at least its length? – DivisionByZero Nov 02 '20 at 17:06
  • @DivisionByZero Yes it is filled. I added it to the question. – Gabriel309 Nov 02 '20 at 17:33
  • This two [1][2] Stackoverflow thread describes how to unsubscribe from Firestore which may be helpful for your issue as a reference. [1] https://stackoverflow.com/questions/44880164/firebase-how-to-unsubscribe [2] https://stackoverflow.com/a/53158150/10415225 – Mohammad I Nov 06 '20 at 02:04
  • thanks @MohammadI, in a lot of other questions people ask about unsubscribing from onSnapshot().subscribe but I however use snapshotChanges().subscribe. I added a reference to my question, this is indeed a good idea! – Gabriel309 Nov 08 '20 at 13:00

0 Answers0