From 476a70e4afb08e15b546a41233fcbbdc72da1b0b Mon Sep 17 00:00:00 2001 From: Plague Fox Date: Sun, 12 May 2024 08:38:52 +0400 Subject: [PATCH] Refactor SpinifyCommandMixin error handling and connection logic --- lib/src/spinify_impl.dart | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/src/spinify_impl.dart b/lib/src/spinify_impl.dart index 7106cf8..9d7df12 100644 --- a/lib/src/spinify_impl.dart +++ b/lib/src/spinify_impl.dart @@ -120,7 +120,7 @@ base mixin SpinifyCommandMixin on SpinifyBase { assert(command.id > -1, 'Command ID should be greater or equal to 0'); assert(_replies[command.id] == null, 'Command ID should be unique'); assert(_transport != null, 'Transport is not connected'); - assert(state.isConnected, 'State is not connected'); + assert(!state.isClosed, 'State is closed'); final completer = _replies[command.id] = Completer(); await _sendCommandAsync(command); return await completer.future.timeout(config.timeout); @@ -135,7 +135,7 @@ base mixin SpinifyCommandMixin on SpinifyBase { Future _sendCommandAsync(SpinifyCommand command) async { assert(command.id > -1, 'Command ID should be greater or equal to 0'); assert(_transport != null, 'Transport is not connected'); - assert(state.isConnected, 'State is not connected'); + assert(!state.isClosed, 'State is closed'); await _transport?.send(command); } @@ -166,9 +166,11 @@ base mixin SpinifyConnectionMixin @override Future connect(String url) async { + if (state.url == url) return; + final completer = _readyCompleter ??= Completer(); + await disconnect(); try { - // Disconnect previous transport if exists. - _transport?.disconnect(1000, 'Reconnecting').ignore(); + _setState(SpinifyState$Connecting(url: url)); // Create new transport. _transport = await _createTransport(url, config.headers) @@ -181,7 +183,6 @@ base mixin SpinifyConnectionMixin final reply = await _sendCommand(request); _setState(SpinifyState$Connected( url: url, - timestamp: DateTime.now(), client: reply.client, version: reply.version, expires: reply.expires, @@ -194,10 +195,11 @@ base mixin SpinifyConnectionMixin )); // Notify ready. - _readyCompleter?.complete(); + if (!completer.isCompleted) completer.complete(); _readyCompleter = null; } on Object catch (error, stackTrace) { - _readyCompleter?.completeError(error, stackTrace); + if (!completer.isCompleted) completer.completeError(error, stackTrace); + _readyCompleter = null; rethrow; } }