public function disconnect()
    {
        if (!$this->isConnected || $this->isDisconnecting) {
            return new RejectedPromise(new \LogicException('The client is not connected.'));
        }

        $this->isDisconnecting = true;

        $deferred = new Deferred();

        $this->startFlow(new OutgoingDisconnectFlow($this->connection), true)
            ->then(function (Connection $connection) use ($deferred) {
                $this->isDisconnecting = false;
                $this->isConnected = false;

                $this->emit('disconnect', [$connection, $this]);
                $deferred->resolve($connection);

                if ($this->stream !== null) {
                    $this->stream->close();
                }
            })
            ->otherwise(function () use ($deferred) {
                $this->isDisconnecting = false;
                $deferred->reject($this->connection);
            });

        return $deferred->promise();
    }