How To Make User Presence Mechanism Using Firebase?
Solution 1:
There are two ways the user can get disconnected from the Firebase Database.
- a clean disconnect, where the client sends a signal to the server before it disconnects.
- a dirty (for lack of a better term) disconnect, where the connection gets closed before the client can send a signal.
In the case of a clean disconnect, your onDisconnect handlers will immediately fire and thus your database will immediately be updated.
In the case of a dirty disconnect, Firebase depends on the socket layer to signal when the remote client is gone. This may take anywhere up to a few minutes. But eventually the server will detect/decide that the client is gone, and your onDisconnect handlers will fire.
A small note in your data structure: you that there is a 1:1 relation between a user and a connection. That is unfortunately not the case.
- A user may be connected from multiple devices. If they now disconnect from one of those devices, the
onDisconnectfrom that device will setonlinetofalsewhile they may still be connected on another device. - Mobile devices/networks have a habit of going through occasional disconnect/reconnect cycles. This means that you may have multiple connections, even on a single device. In case of a dirty disconnect, the
onDisconnecthandler may be fired much later, when you've already setonlinetotruefor the new connection. In such a case, your lingeringonDisconnecthandler will setonlinetofalsewhile the user may already be reconnected.
All this is to say that you should not rely on having a 1:1 relation between a user and their connection(s). The samples in the Firebase documentation treat connections as a collection and assume that the user is connected as long as there is any "connect ID" (generated by push()) left for that user. I recommend you do the same to prevent hard to debug race conditions and connection problems.
Post a Comment for "How To Make User Presence Mechanism Using Firebase?"