MQTT.js icon indicating copy to clipboard operation
MQTT.js copied to clipboard

The unsubscribe method of MQTT.js is not working properly.

Open lucaspedro opened this issue 4 years ago • 3 comments

During the implementation of a code I realized that my topics registered in mqtt.js were not removed from the registry when calling the unsubscribe function. Thus, in the case of dynamic components that needed to open and close their topics by demand, the code was lost and did not receive the values in a timely manner (when it did). I did some research and apparently was making the correct use of the function, but the behavior was not ideal, to correct this problem I had to implement my own unsubscribe, I will share it below:

/* Clean a list of topics. */
    destroyTopics(topics) {
      topics.map((topic) => {
        this.destroyTopic(topic)
      })
    },
    /* Clean only one topic. */
    destroyTopic(topic) {
      this.$mqtt2.unsubscribe(topic)
      for (const key in this.$mqtt2.messageIdToTopic) {
        for (let i = 0; i < this.$mqtt2.messageIdToTopic[key].length; i++) {
          let elem = this.$mqtt2.messageIdToTopic[key][i]
          if (elem == topic) {
            this.$mqtt2.messageIdToTopic[key].splice(i, 1);
          }
        }
        if (this.$mqtt2.messageIdToTopic[key].length<=0)
          delete this.$mqtt2.messageIdToTopic[key]
      }
    },

But I hope that the lib updates and corrects this problem on its own, since the ideal is that this process is carried out by itself.

lucaspedro avatar Jun 25 '20 13:06 lucaspedro

Even I am faced the same issue while unsubscribing topics during run time

Mailari avatar Aug 07 '20 18:08 Mailari

Had same issue, with mqttjs v4.2.4. the callback in unsubscribe doesnt raise any error. So i delete the key after calling unsubscribe.

topics = this.$mqtt.messageIdToTopic
topicExits = Object.keys(topics).find(
  k => String(topics[k]) === targetMqttTopic
)
if (topicExits !== undefined) {
  this.$mqtt.unsubscribe(targetMqttTopic)
  delete this.$mqtt.messageIdToTopic[topicExits]
}

hpo14 avatar Nov 04 '20 10:11 hpo14

Im running into this in a react app, weird that this isnt handled. Its basically impossible to handle messages at most once.

oneEyedSunday avatar May 24 '22 17:05 oneEyedSunday

This is an automated message to let you know that this issue has gone 365 days without any activity. In order to ensure that we work on issues that still matter, this issue will be closed in 14 days.

If this issue is still important, you can simply comment with a "bump" to keep it open.

Thank you for your contribution.

github-actions[bot] avatar May 25 '23 01:05 github-actions[bot]

This issue was automatically closed due to inactivity.

github-actions[bot] avatar Jun 08 '23 02:06 github-actions[bot]