【问题标题】:firebase onDisconnect() is not fired when user lose connection当用户失去连接时,firebase onDisconnect() 不会被触发
【发布时间】:2019-10-29 04:26:30
【问题描述】:
您好 React 本地社区,我正在尝试在 firebase 中使用 onDisconnect(),但问题是当网络失去连接时 void 不会被触发,但如果我关闭应用程序或当我关闭应用程序时它正在工作应用崩溃。
此代码在 Wi-Fi 开启时有效,但在 Wi-Fi 关闭时根本不起作用..
firebase.database().ref('users/test/connected').onDisconnect().set(false)
有什么想法吗?
【问题讨论】:
标签:
firebase
react-native
【解决方案1】:
您可以将断开连接操作与连接状态监控和服务器时间戳相结合,构建用户连接状态系统。在这个系统上,每个用户都将数据存储在特定的数据库位置,以提醒实时数据库客户端在线。客户端在联机时将此位置设置为 true,并在断开连接时设置时间戳。此时间戳表示用户上次在线的时间。
应用程序在用户在线显示之前有一个断开操作,因此如果客户端在两个命令发送到服务器之前失去网络连接,则不会发生争用。
// since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/test/connections');
// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/test/lastOnline');
var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on('value', function(snap) {
if (snap.val() === true) {
// We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
var con = myConnectionsRef.push();
// When I disconnect, remove this device
con.onDisconnect().remove();
// Add this device to my connections list
// this value could contain info about the device or a timestamp too
con.set(true);
// When I disconnect, update the last time I was seen online
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
}
});