diff --git a/lib/src/support/websocket/io.dart b/lib/src/support/websocket/io.dart index 22f6522..65102ba 100644 --- a/lib/src/support/websocket/io.dart +++ b/lib/src/support/websocket/io.dart @@ -22,23 +22,24 @@ class LiveKitWebSocketIO implements LiveKitWebSocket { ]) { _subscription = _ws.listen( (dynamic data) => options?.onData?.call(data), - onDone: () => dispose(), + onDone: () async { + await _subscription.cancel(); + options?.onDispose?.call(); + }, ); } @override Future dispose() async { - await _subscription.cancel(); - await _ws.close(); - options?.onDispose?.call(); + if (_ws.readyState != io.WebSocket.closed) { + await _ws.close(); + } } @override void send(List data) { - // 0 CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED - if (_ws.readyState != 1) { - logger.fine( - '[$objectId] Tried to send data (readyState: ${_ws.readyState})'); + if (_ws.readyState != io.WebSocket.open) { + logger.fine('[$objectId] Socket not open (state: ${_ws.readyState})'); return; } diff --git a/lib/src/support/websocket/web.dart b/lib/src/support/websocket/web.dart index 5cd5411..dce987d 100644 --- a/lib/src/support/websocket/web.dart +++ b/lib/src/support/websocket/web.dart @@ -27,7 +27,11 @@ class LiveKitWebSocketWeb implements LiveKitWebSocket { dynamic _data = _.data is ByteBuffer ? _.data.asUint8List() : _.data; options?.onData?.call(_data); }); - _closeSubscription = _ws.onClose.listen((_) => dispose()); + _closeSubscription = _ws.onClose.listen((_) async { + await _messageSubscription.cancel(); + await _closeSubscription.cancel(); + options?.onDispose?.call(); + }); } @override @@ -35,10 +39,9 @@ class LiveKitWebSocketWeb implements LiveKitWebSocket { @override Future dispose() async { - options?.onDispose?.call(); - await _messageSubscription.cancel(); - await _closeSubscription.cancel(); - _ws.close(); + if (_ws.readyState != html.WebSocket.CLOSED) { + _ws.close(); + } } static Future connect(