Connection State
Observable connection lifecycle state for MqttClient.
Collect MqttClient.connectionState as a kotlinx.coroutines.flow.StateFlow to observe state transitions and react to connectivity changes — including the underlying cause when a connection drops or a reconnect attempt fails.
Typical lifecycle: Disconnected → Connecting → Connected → Disconnected. When auto-reconnect is enabled and a connection drops unexpectedly: Connected → Reconnecting → Connected (or Disconnected on permanent failure).
Example — react to disconnect reasons
client.connectionState.collect { state ->
when (state) {
is ConnectionState.Connected -> println("Online")
is ConnectionState.Connecting -> println("Connecting...")
is ConnectionState.Reconnecting -> println("Reconnecting (attempt ${state.attempt})")
is ConnectionState.Disconnected -> when (val reason = state.reason) {
null -> println("Offline")
else -> println("Offline: ${reason.reasonCode} — ${reason.message}")
}
}
}Migration from 0.1.x
In 0.1.x ConnectionState was an enum with CONNECTING/CONNECTED/DISCONNECTED/ RECONNECTING constants. Replace equality checks (state == ConnectionState.CONNECTED) with is checks (state is ConnectionState.Connected).
Inheritors
Types
Successfully connected to the broker and ready for publish/subscribe operations.
Actively establishing a connection to the broker.
Not connected to any broker.
Attempting to re-establish a lost connection.