Firestore:根据函数参数关闭 onSnapshot 侦听器不起作用

Firestore: Turning off onSnapshot listener doesn't work based on function argument

在我的带有 Firestore (Firebase 9) 的网络应用程序中,我有以下代码,它应该根据 getRecentProfilesExternal() 函数中的参数关闭实时侦听器。它在 ACTION1 中有效,但在 ACTION2 中无效。

奇怪的是,我在 ACTION2 中收到“取消订阅”警报,尽管侦听器仍然处于活动状态。

感谢您的帮助!

//Get profiles and update them in realtime

    //The command param determines if the function should subscribe to changes (leave the onSnapshot listener on), 
    //or unsubscribe (in order to limit Firestore reads), usually when another listener is turned on instead

    const getRecentProfilesExternal = (command) => {


        //Get loggedin user data
        const auth = getAuth();
        onAuthStateChanged(auth, (user) => {
            if (user) {


              //Get last 20 profiles: initial render and listen to changes
              const qProfiles = query(collection(db, "candidateprofiles"), where("useridprimary", "==", store.state.currentUserId));
              //initial data fetch and listen to Firestore collection changes
              const unsubscribe = onSnapshot(qProfiles, (snapshot) => {
                store.state.currentProfileList = []
                snapshot.docs.forEach((doc) => {
                  let profile = doc.data()
                  profile.id = doc.id
                  store.state.currentProfileList.push(profile)
                })
              })

              //ACTION 1
              setTimeout(() => {
                unsubscribe()
              }, 5000);

              //ACTION 2
              if(command == "unsubscribe") {
                //this turns the onSnapshot listener off
                unsubscribe()
                alert("unsubscribed")
              }
              else {
                //do nothing, this will keep the onSnapshot listener turned on
              }

   
            } else {
                //user not signed in
            }
        });
    }

        

所以我才意识到,当我第二次调用该函数时,它会订阅,然后订阅一个新的侦听器。但是老听众仍然很活跃。所以现在我的问题是当函数已经 运行 第一次打开监听器时,如何稍后触发 unsubscribe() 。我无法在函数外访问 unsibscribe()。

所以我通过声明一个名为 unsubscribeToRecentProfiles 的全局变量来解决它。然后在初始函数中为该变量分配 onSnapshot 代码。现在我可以创建第二个函数 运行 取消订阅,因为它具有全局范围。不是很优雅,但我现在看不到更好的方法。这是我的解决方案:

let unsubscribeToRecentProfiles;

  //Get profiles and update them in realtime
  const getRecentProfiles = () => {

      //Get loggedin user data
      const auth = getAuth();
      onAuthStateChanged(auth, (user) => {
          if (user) {

            const qProfiles = query(collection(db, "candidateprofiles"), where("useridprimary", "==", store.state.currentUserId));
            unsubscribeToRecentProfiles = onSnapshot(qProfiles, (snapshot) => {
              store.state.currentProfileList = []
              snapshot.docs.forEach((doc) => {
                let profile = doc.data()
                profile.id = doc.id
                store.state.currentProfileList.push(profile)
              })
            })

          } else {
              //user not signed in
          }
      });
  }

  unsubscribeToRecentProfiles()