简体   繁体   中英

Firebase Firestore Unsubscribe to SnapShot in for loop

I am working with firebase firestore and I have set of data from collection that I am taking in snapshot which is in for loop.

To avoid multiple time query the data base I have created data service mechnism to use the local array to display and I am handling it through rxjs subject behaviour.

Issue here is if user deleted some document from application I have removed it from firebase and then from local still its snapshot we have to manually unsubscribe that

I know the basic method which is like this..

var unsubscribe = db.collection("cities")
    .onSnapshot(function () {});
// ...
// Stop listening to changes
unsubscribe();

This is not applicable in my case as I am taking snapshot in for loop like this

   getSnapShot() {
        this.global.currentUser.shortlist.forEach((propertyID: any) => {
          this.getSnapShotByID(ID);
        });
      }
    getSnapShotByID(ID) {
        // return new Observable((observe: Observer<any>) => {
        this.db.collection('properties').doc(propertyID).onSnapshot((snapshot: any) => {
//HERE I AM ADDING PROPERTY IN LOCAL ARRAY
    ....
    }

Now when user Delete Property from collection I have to unsubscribe otherwise it will keep listening and changing my local array

any suggestion idea?

For your use case, I can recommend below approach

As you are taking the entire copy of data in RXJS subject. Where delete is happening inside your for loop delete the data which is not required from the existing Rxjs behaviour subject and again re push the new data after deletion by using the next operator. So your observable is also updated with the latest data along with firebase database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM