当用户失去连接时,firebase onDisconnect()不会被激发



Hello React原生社区,我正试图在firebase中使用onDisconnect(),但问题是,当网络失去连接时,void不会被激发,但如果我关闭应用程序或应用程序崩溃,它会起作用。

如果Wi-Fi打开,此代码有效,但如果Wi-Fi关闭,则根本不起作用。

firebase.database().ref('users/test/connected').onDisconnect().set(false)

有什么想法吗?

您可以将断开连接操作与连接状态监视和服务器时间戳相结合,以构建用户连接状态系统。在该系统中,每个用户都将数据存储在特定的数据库位置,以提醒实时数据库客户端联机。客户端在联机时将此位置设置为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);
}
});

最新更新