I am currently developing a real-time application where one user can enter the app, and all other users connected to that session will receive notifications or payloads of what that user is entering.
Below is the Firebase child_changed listener that every device in the session is listening to:
firebase.database().ref().child('collection')
.orderByChild('sessionId')
.equalTo('123') //unique id
.on('child_changed', function (snapshot) {
//performing some processing
});
Whenever a user enters the app, I update the Firebase document/collection as follows:
var newObject = {},
fbId = 'Kh8nyd9C1FGeBx229ogyr';// unique id of document to be updated
newObject[fbId] = {
'sessionId': '123',
'payLoad': JSON.stringify(payLoad), //different payload for each device listening to the collection within this session
'lastUpdated': new Date().getTime() //adding a unique timestamp to trigger the child_changed event
};
firebase.database().ref().child('collection').update(newObject);
//rules
"rules": {
"$uid": {
"collection": {
".read": "auth.uid == $uid",
".write": "auth.uid == $uid",
".indexOn": ["sessionlId"]
}
}
}
//data
{
"Azublidegytttsbmnmnmnm": { //uid
"collection": {
"Kh8nyd9C1FGeBx229ogyr": {
"sessionId": 123,
"payLoad": {Id: '11', Name: 'John Doe'},
"lastUpdated": 1543875382963
}
}
}
}
The above code works most of the time but misses events if a browser tab remains idle for an extended period. In such cases, it fails to receive events or trigger the child_changed event when a new user enters while another connected user's tab is inactive. Refreshing the browser helps reset the Firebase connection code and restores proper functionality.
Any assistance on ensuring that the child_changed event fires consistently would be greatly appreciated. Alternatively, feel free to suggest any other approaches to address this issue.
I am using version 3.5.3 of the Firebase library.
Thank you!