androidmqttdisconnecthivemqandroid-mqtt-client

Hive MqttClient DisconnectedListener takes forever (Android)


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?


Solution

  • 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 {}