0

I am using the Hive Mqtt Library zu create a mqttclient. I added addDisconnectedListener because i need to change my view according to the connection state. The problem is that the callback is delayed. The callback takes 60 seconds on average to arrive.

At first i thought that it's because of the automatic reconnect. Maybe the reconnect is blocking the disconnected state to be set.

Mqtt5Client.builder()
            .identifier(UUID.randomUUID().toString())
            .serverHost(inetAddress)
            .automaticReconnect()
            .initialDelay(500, TimeUnit.MILLISECONDS)
            .maxDelay(10, TimeUnit.SECONDS)
            .applyAutomaticReconnect()
            .addDisconnectedListener {
                _clientConnectionState.value = false
            }
           
            .addConnectedListener {
                Napier.d("MqttClient connected")
            }
            .buildAsync()

So i tried to implement the reconnect inside the DisconnectedListener so the reconnect can't interfere if it is only starting after the callback arrives but it didn't help.

Mqtt5Client.builder()
            .identifier(UUID.randomUUID().toString())
            .serverHost(inetAddress)
            .addDisconnectedListener { context ->
                context.reconnector
                    .reconnect(true)
                    .delay(2, TimeUnit.SECONDS)
            }
            .addConnectedListener {
                Napier.d("MqttClient connected")
            }
            .buildAsync()

Anybody had the same problem and knows how to fix it?

froots
  • 53
  • 3

1 Answers1

0

Ok the problem was the keepAlive interval. On default its set to 60 seconds.

Changing this

client.connect().whenComplete {}

to this worked.

client.connectWith().keepAlive(1).send().whenComplete {}
JustSightseeing
  • 1,460
  • 3
  • 17
  • 37
froots
  • 53
  • 3
  • Setting the keepalive to 1 second is going to generate a lot more network traffic for the client if you have relatively quiet topics. (and also potentially a lot of load for the broker if you have a lot of clients) – hardillb Feb 23 '23 at 11:22
  • Each client has its own broker connected via ethernet. So the broker will be able to handle it. I really need to get the callback for the disconnect immediately thats why i set it to 1. The application is only for demo purposes so its fine by now but it's a good tip when thinking about a larger scale. Thanks – froots Feb 24 '23 at 11:05