Currently this is not supported in paho java library, but I need this functionality in our application. For example, on application startup, we didn't have network connection, but after 30 seconds or so, we established connection successfully so I want my client to connect automatically.
My question is - what would be best approach to accomplish this? What I tried so far is to try to reconnect if something goes wrong during connect method. And since we use RxJava I have scheduled execution of the same method which is responsible for client connection. It will be easier if I paste the code.
private void connect(String brokerUrl) {
try {
LOG.info("Connecting to the broker...");
mqttClient.connect(connectionOptions, "Connecting", new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
LOG.info("Successfully conected to the broker.");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LOG.error("Failed to connect to broker. Trying to reconnect in {} milliseconds...", connectionRetryTimeout, exception);
// try to reconnect in few seconds
Schedulers.io().scheduleDirect(() -> connect(brokerUrl), connectionRetryTimeout, TimeUnit.MILLISECONDS);
}
});
} catch (MqttException e) {
LOG.error("Connection error.", e);
}
}
What happens like this is that, when network connection is available I manage to connect automatically, but second thread is created which continues to retry to connect to broker. Does anyone already implemented this, or do you have any other suggestions?