I am creating a flutter app, it would be essential to detect almost immediately a user goes offline from the realtime/firestore database and notify other users of the same.
I have tried the recommended method of subscribing to .info/connected in the realtime DB and also update a firestore DB.
FirebaseDatabase.instance
.reference()
.child('.info')
.child('connected')
.onValue
.listen((data) {
if (data.snapshot.value == false) {
// Internet has been disconnected
setState(() {
state.connected = false;
});
userFirestoreRef.updateData({
'status': 'offline',
'lastChanged': FieldValue.serverTimestamp(),
});
}
userDbRef.onDisconnect().update({
'status': 'offline',
'lastChanged': ServerValue.timestamp
}).then((_) async {
// This resolves as soon as the server gets the request, not when the user disconnects
setState(() {
state.connected = true;
});
await userDbRef.update({
'status': 'online',
'lastChanged': ServerValue.timestamp,
}).catchError((e) => debugPrint('Error in realtime db auth, $e'));
await userFirestoreRef.updateData({
'status': 'online',
'lastChanged': FieldValue.serverTimestamp(),
}).catchError((e) => debugPrint('Error in firestore auth, $e'));
});
Once the internet is off, it takes about 1.5 minutes for the realtime db to detect the user disconnected, I would like this to maybe be 10 seconds maximum.