How to subscribe to two different topics using MQTT java client?.
//Example code with single topic sub: SUCCESS
mqtt3AsyncClient.subscribeWith().topicFilter(“tenant1/topic”)
.qos(MqttQos.AT_LEAST_ONCE).callback(e -> {}).send();
//Subscribing to two topics : FAILED
mqtt3AsyncClient.subscribeWith().topicFilter(“tenant1/topic”).topicFilter(“tenant2/topic”)
.qos(MqttQos.AT_LEAST_ONCE).callback(e -> {}).send();
It means that you should not implement the interface for custom logic to avoid unwanted behaviour, instead you should use the provided implementation (in this case the builder).
For the second point, for an out of the box solution you will need to wait for the 1.2 release of the client (see https://github.com/hivemq/hivemq-mqtt-client/issues/170).
As I also needed this feature I can give you a workaround (adapt as needed) that you could use in the meantime:
// connect client
final List<String> topics = List.of("test", "topic", "asdf", "qwer");
final int subCount = topics.size();
final Mqtt3SubscribeBuilder builder = Mqtt3Subscribe.builder();
Mqtt3Subscribe beeSubscribe = null;
for (int i = 0; i < subCount; i++) {
final String topic = topics.get(i);
final Mqtt3Subscription beeSubscription = Mqtt3Subscription.builder().
topicFilter(topic).qos(MqttQos.AT_LEAST_ONCE).build();
if (i + 1 == subCount) {
// build the subscribe if it is the last loop iteration
beeSubscribe = builder.addSubscription(beeSubscription).build();
} else {
builder.addSubscription(beeSubscription);
}
}
if (beeSubscribe != null) {
client.subscribe(beeSubscribe).get();
} else {
throw new NullPointerException("Should not happen");
}