【问题标题】:Do Firebase FIrestore Listeners unsubscribe when app is closed?关闭应用程序时,Firebase FIrestore 侦听器是否取消订阅?
【发布时间】:2020-07-05 15:05:30
【问题描述】:

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

如果没有,那么当应用在 React Native 中关闭时如何取消订阅所有 firestore 监听器?

【问题讨论】:

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


    【解决方案1】:

    如果您使用的是实时数据库,您可以使用componentDidUnMount 循环挂钩。

    更新:正如 puf 所注意到的,您使用的是 Firestore,所以我将包括两种方式,确保您选择适合您的方式。注意firestore,onSnapshot返回一个取消订阅函数,你可以在cyclehook上使用它。

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

    【讨论】:

    • 好答案。但 OP 使用的是 Firestore,而不是实时数据库。
    • ops ^^ 天哪!
    【解决方案2】:

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

    我仍然建议明确取消订阅,正如@andresmijares 在他们的回答中所显示的那样。

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2021-02-27
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多