您好,React本机社区,我正在尝试在onDisconnect()
中使用firebase
,但是问题是,当网络断开连接时,空白不会被触发,但是如果我关闭,它就会起作用应用程序或应用程序崩溃时。
如果Wi-Fi开启,此代码将起作用,但如果Wi-Fi关闭,则此代码将完全不起作用。
firebase.database().ref('users/test/connected').onDisconnect().set(false)
有什么想法吗?
答案 0 :(得分:0)
您可以将断开连接操作与连接状态监视和服务器时间戳结合使用,以构建用户连接状态系统。在该系统上,每个用户将数据存储在特定的数据库位置,以提醒实时数据库客户端联机。客户端在联机时将此位置设置为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);
}
});