Skip to content

Commit 6186686

Browse files
committed
feat(flutter): realtime heartbeat
1 parent 481487d commit 6186686

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

templates/flutter/lib/src/realtime_mixin.dart.twig

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,33 @@ mixin RealtimeMixin {
2727
int _retries = 0;
2828
StreamSubscription? _websocketSubscription;
2929
bool _creatingSocket = false;
30+
Timer? _heartbeatTimer;
3031

3132
Future<dynamic> _closeConnection() async {
33+
_stopHeartbeat();
3234
await _websocketSubscription?.cancel();
3335
await _websok?.sink.close(status.normalClosure, 'Ending session');
3436
_lastUrl = null;
3537
_retries = 0;
3638
_reconnect = false;
3739
}
3840

41+
void _startHeartbeat() {
42+
_stopHeartbeat();
43+
_heartbeatTimer = Timer.periodic(Duration(seconds: 20), (_) {
44+
if (_websok != null) {
45+
_websok!.sink.add(jsonEncode({
46+
"type": "ping"
47+
}));
48+
}
49+
});
50+
}
51+
52+
void _stopHeartbeat() {
53+
_heartbeatTimer?.cancel();
54+
_heartbeatTimer = null;
55+
}
56+
3957
_createSocket() async {
4058
if(_creatingSocket || _channels.isEmpty) return;
4159
_creatingSocket = true;
@@ -78,6 +96,10 @@ mixin RealtimeMixin {
7896
}));
7997
}
8098
}
99+
_startHeartbeat(); // Start heartbeat after successful connection
100+
break;
101+
case 'pong':
102+
debugPrint('Received heartbeat response from realtime server');
81103
break;
82104
case 'event':
83105
final message = RealtimeMessage.fromMap(data.data);
@@ -91,8 +113,10 @@ mixin RealtimeMixin {
91113
break;
92114
}
93115
}, onDone: () {
116+
_stopHeartbeat();
94117
_retry();
95118
}, onError: (err, stack) {
119+
_stopHeartbeat();
96120
for (var subscription in _subscriptions.values) {
97121
subscription.controller.addError(err, stack);
98122
}
@@ -187,4 +211,4 @@ mixin RealtimeMixin {
187211
_retry();
188212
}
189213
}
190-
}
214+
}

0 commit comments

Comments
 (0)