断开连接时更新Firebase [英] Firebase update on disconnect

查看:44
本文介绍了断开连接时更新Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在firebase上有一个节点,列出了游戏中的所有玩家.新玩家加入时,此列表将更新.当当前用户(me)断开连接时,我想从列表中删除自己.

I have a node on firebase that lists all the players in the game. This list will update as and when new players join. And when the current user ( me ) disconnects, I would like to remove myself from the list.

由于列表会随着时间变化,因此在我断开连接的那一刻,我想更新此列表并更新Firebase.

As the list will change over time, at the moment I disconnect, I would like to update this list and update firebase.

这是我正在考虑的方式,但是它不起作用,因为.update不接受功能.只有对象.但是,如果我事先创建了对象,那么当.onDisconnect调用时,它将不是最新的对象...我应该如何去做?

This is the way I am thinking of doing it, but it doesn't work as .update doesnt accept a function. Only the object. But if I create the object beforehand, when .onDisconnect calls, it will not be the latest object... How should I go about doing this?

payload.onDisconnect().update( () => {
            const withoutMe = state.roomObj
            const index = withoutMe.players.indexOf( state.userObj.name )
            if ( index > -1 ) {
                withoutMe.players.splice( index, 1 )
            }
            return withoutMe
        })

推荐答案

为此用例创建了 onDisconnect 处理程序.但这要求您在设置 onDisconnect 时知道写操作的数据.如果您考虑一下,这应该是有道理的:由于 onDisconnect 之后断开连接后发生,因此必须知道该写操作的数据之前.

The onDisconnect handler was made for this use-case. But it requires that the data of the write operation is known at the time that you set the onDisconnect. If you think about it, this should make sense: since the onDisconnect happens after your client is disconnected, the data of the data of that write operation must be known before the disconnect.

听起来您正在构建一个所谓的状态系统:一个列表,其中包含每个当前在线用户的节点. Firebase文档中有这样的状态系统示例.与您的方法的主要区别在于,每个用户在文档中仅修改自己的节点.

It sounds like you're building a so-called presence system: a list that contains a node for each user that is currently online. The Firebase documentation has an example of such a presence system. The key difference from your approach is that it in the documentation each user only modifies their own node.

因此:当用户上线时,他们会为自己编写一个节点.然后,当它们断开连接时,该节点将被删除.由于所有用户都将其节点写在同一个父节点下,因此该父节点将反映在线用户.

So: when the user comes online, they write a node for themselves. And then when they get disconnected, that node gets removed. Since all users write their node under the same parent, that parent will reflect the users that are online.

实际的实现还涉及更多点,因为它也处理一些边缘情况.因此,我建议您检查我链接的文档中的代码,并将其用作您自己的类似系统的基础.

The actual implementation is a bit more involved since it deals with some edge cases too. So I recommend you check out the code in the documentation I linked, and use that as the basis for your own similar system.

这篇关于断开连接时更新Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆