close method

Future<void> close()

Closes the connection and the stream.

This cancels the internal subscription on the WebSocket channel, closes the underlying connection, and closes the stream so that listeners always receive a done event.

Implementation

Future<void> close() async {
  await _subscription?.cancel();

  try {
    await _channel.sink.close();
  } catch (_) {
    //! Never let errors while closing the underlying channel
    //! prevent the stream from being closed.
  }

  if (!_controller.isClosed) {
    //! Don't await: the future returned by [StreamController.close]
    //! completes only after a listener has received the done event,
    //! and would therefore hang if the stream is never listened to.
    unawaited(_controller.close());
  }
}