关闭应用程序后,Firebase FIrestore Listeners是否取消订阅?

时间:2020-07-05 15:05:30

标签: firebase react-native google-cloud-firestore

我有一个应用程序,可以监听Firestore实时快照。我想问一下关闭该应用程序是否会取消所有侦听器的订阅?

如果没有,那么当应用程序在React Native中关闭时,如何退订所有Firestore侦听器?

2 个答案:

答案 0 :(得分:0)

如果您正在使用实时数据库,则可以使用componentDidUnMount循环钩子。

更新:正如puf所注意到的,您正在使用Firestore,因此我将同时提供两种方式,请确保您为自己选择了正确的方式。请注意,在使用Firestore的情况下,onSnapshot返回一个取消订阅的函数,您可以在循环钩子上使用它。

class YourComponent extends React.Component {
   constructor(props) {
      super(props)
        this.realtimeDB = firebase.database().ref().child('yourNode') /* ... etc...*/
        this.firestoreDB = null
        this.state = { something: [] }
    }

    componentDidMount () {
       const colRef = firebase.firestore().collection("your_collection").doc(YOURDOCID)
        this.firestoreDB = colRef.onSnapshot(function(querySnapshot) {
            var something = [];
             querySnapshot.forEach(function(doc) {
               something.push(doc.data());
             });
            that.setState({ something })
        });
    }
    

   componentWillUnMount() {
       this.realTimeDB.off()
    
       this.firestoreDB()
   }
}

答案 1 :(得分:0)

当应用程序关闭时,Firebase不会自动关闭所有侦听器。但是您的操作系统通常会在关闭应用程序时关闭所有此类连接。

尽管如此,我仍然建议您明确取消订阅,如@andresmijares在其答案中所示。