Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

480
Vistas
Firestore: desactivar el oyente onSnapshot no funciona según el argumento de la función

En mi aplicación web con Firestore (Firebase 9), tengo el siguiente código que debería desactivar un oyente en tiempo real según el argumento de la función getRecentProfilesExternal(). Funciona en ACTION1 pero no en ACTION2.

Extrañamente, recibo la alerta de "suscripción cancelada" en ACTION2 aunque el oyente permanece activo.

¡Gracias por cualquier ayuda!

 //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 } }); }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Entonces me di cuenta de que cuando llamo a la función por segunda vez, se suscribe y luego se suscribe a un nuevo oyente. Pero el viejo oyente sigue activo. Así que ahora mi problema era cómo activar unsubscribe() más tarde, cuando la función ya se ejecutó por primera vez para activar el oyente. No tenía acceso a unsibscribe() fuera de la función.

Así que lo resolví declarando una variable global llamada unsubscribeToRecentProfiles. Luego, a esta variable se le asigna el código onSnapshot en la función inicial. Ahora puedo crear una segunda función que ejecuta la cancelación de suscripción ya que tiene un alcance global. No es muy elegante, pero no veo una mejor manera en este momento. Esta es mi solución:

 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()

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda