firebasegoogle-cloud-firestoreangularfire2

Angularfire snapshotChanges() vs Firestore JavaScript library onSnapshot()


I found there are two realtime listeners for firestore.

Here is my question

  1. What is the difference? How should I use them properly (I'm developing using Ionic + Cordova + Angular framework)?

  2. How to detach snapshotChanges()? Refer to Firestore documentation, I can detach onSnapshot() as per below.

var unsubscribe = db.collection("cities")
    .onSnapshot(function (){
      // Respond to data
      // ...
    });

// Later ...

// Stop listening to changes
unsubscribe();

Solution

  • AngularFire library does not contain a method called onSnapshot(). The onSnapshot() method is used in the javascript cloud firestore library, to listen for realtime updates.

    While the snapshotChanges() is specifically for angularfire it returns an Observable therefore it will keep listening for any changes in the database and retrieve the data.

    To unsubscribe, you just need to call the method unsubscribe():

    //Subscribe
    subscription = this.itemRef.snapshotChanges().subscribe();
    
    //Unsubscribe
    subscription.unsubscribe()