HiveMQ

Cancel automatic reconnects

I found that the running automatic reconnects (e.g. for authentication failure) are not stopped even by calling mqttClient.disconnect(). In this state ending the activity can even produce a memory leak.

According to https://github.com/hivemq/hivemq-mqtt-client/issues/306 we can apply following code to cancel reconnects:

  final AtomicBoolean cancelReconnect = new AtomicBoolean(false);
  Mqtt3Client.builder()
        .automaticReconnectWithDefaultConfig()
        .addDisconnectedListener(context -> {
            if (cancelReconnect.get()) {
                context.getReconnector().reconnect(false);
            }
        })
    ...

Is it possible to subclass the Mqtt3AsyncClient in order to make cancelReconnect an object field and make some method like this available:

public void cancelReconnects() {
    this.cancelReconnect.set(true);
}

Or do I have to make a wrapper?

Or is there a better way to tell the client to stop anything as it’s going to be destroyed?