简体   繁体   中英

how to unsubscribe nested real time firebase cloud firestore database?

I'm new to web development. I'm trying to unsubscribe real time listener from firestore with nested listening for relations. I tried let unsub = db.collection().onSnapshot(()=>{}); unsub(); unsub = db.collection().onSnapshot(()=>{}); unsub(); from firestore document, but it doesn't work.

It's a nested listener something like:

 db.collection('apple_orange').where('orange_id','==',orangeID).onSnapshot((querySnapshot=>{
    querySnapshot.docChanges().forEach(change => {
      if(change.type ==='added'){
          db.collection('apple_mango').where('apple_id','==',change.doc.data().appleID).onSnapshot((querySnapshot=>{
            querySnapshot.docChanges().forEach(change=>{
              if(change.type === 'added'){
                  // do something
              }
            })
          }))
      }
      if(change.type ==='removed'){
        //unsubscribe listener of apple_mango query
        let unsub = db.collection('apple_mango').where('apple_id','==',change.doc.data().appleID).onSnapshot(()=>{})
        unsub()
      }

    });
  }))

Is it even possible to do this? Please help.

Don't create a new Query to unsubscribe. Use the unsubscribe function from the original Query.

const unsub = db.collection(...).where(...).onSnapshot(querySnapshot => {
    if (time_to_unsub) {
        unsub()
    }
})

You might have to change the scope of unsub to match what you're trying to do. But either way, don't create a new Query just to unsubscribe.

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