How to avoid subscribing to the same topic and fire the callback multiple times in HiveMQ Android Client?

Expected behavior

I want to have a callback to listen to every topic I subscribe to just once per message sent. I mean, I want to subscribe to a topic 1000 times, but when a message is received, I want to listen to it just one time.

IDK if there is something I am doing wrong (I guess).

Actual behavior

  • I am developing a home security camera app.
  • I have a list of cameras that I own.
  • For every camera on the list, I subscribe to a topic.
  • Every 30s, I update the screen, and again I subscribe to a topic for every camera. This means a TOPIC could be subscribed many times.
  • Every time I receive a message on a topic, the callback fires messages about how many times the same topi was subscribed.

To Reproduce


  1. haven a topic camera/123
  2. subscribe the topic N times with the below method called subscribeWith
  3. Send a message over camera/123
  4. You will receive the message N times because the N time you subscribed to the topic

Reproducer code

Just variables

private var mqtt: Mqtt5AsyncClient? = null
private var username: String? = null
private var password: String? = null
private val serverHost: String,
private val serverPort: Int = 1883

Build the MQTT

private fun build() {
        if (mqtt != null) return

        mqtt = Mqtt5Client.builder()
                .addConnectedListener { Timber.d("On Connected") }
                .addDisconnectedListener { onMQTTDisconnected(it) }

Connecting the MQTT

fun connect(username: String, password: String) {

        this.username = username
        this.password = password


And then, subscribing a topic
Every time I subscribe a topic I use these fun

fun subscribeWith(topic: String) {
               ?.callback { t -> onConsumingTopic(t) }  <- I THINK THIS IS THE IMPORTANT THING
                ?.whenComplete { ack, error -> onTopicConnected(ack, error, topic) }


Hello @denebchorny.hipcam

Welcome to HiveMQ Community Forum. Glad to see you’re taking interest in HiveMQ

Thanks for your patience.

The callback will be executed as and when you subscribe to topic(same or different topic). This is the expected behaviour of callback. We would like to recommend here is do not subscribe twice to the same topic.

I hope this helps.

Kind regards,