Skip to content

Conversation

@pglombardo
Copy link
Contributor

@pglombardo pglombardo commented Oct 27, 2025

Description

This PR adds a new disconnectGracefully method to all interfaces for MQTT 3 & 5.

Previously, if a connected client (with reconnect enabled) loses network (e.g. device sleep or interface down), calling disconnect would raise MqttClientStateException: MQTT client is not connected. and reconnection would continue with no way to stop the reconnection attempts.

Internally, this happens because the automatic reconnection only stops if the disconnect source is USER. When the network is turned off, the disconnect source is CLIENT (network error) and the client gets into an uncontrollable state.

Per #675, users need to be able to cleanly shut down their MQTT clients regardless of the current connection state.

To do this, we add a new client state DISCONNECTING_GRACEFULLY and update the reconnection logic to respect this state.

disconnectGracefully() is added to all MQTT 3 & 5 interfaces with tests to validate.

Related Issue

#675

Type of Change

  • 📚 Examples / docs / tutorials / dependencies update
  • 🔧 Bug fix (non-breaking change which fixes an issue)
  • 🥂 Improvement (non-breaking change which improves an existing feature)
  • 🚀 New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to change)
  • 🔐 Security fix

Checklist

  • I've written tests (if applicable) for all new methods and classes that I created.
  • I've added documentation as necessary so users can easily use and understand this feature/fix.

// If not connected, just complete successfully for graceful disconnect
EmptyDisposable.complete(s);
return;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connectionConfig will be null when a connection was never established due to an unavailable server or wrong configuration. In this case, the disconnection attempt is abandoned here and the auto-reconnect loop will still continue endlessly.

Tested with Mqtt3AsyncClient

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants