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).
// 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");
}