MQTT.js
MQTT.js copied to clipboard
The unsubscribe method of MQTT.js is not working properly.
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.
Even I am faced the same issue while unsubscribing topics during run time
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]
}
Im running into this in a react app, weird that this isnt handled. Its basically impossible to handle messages at most once.
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.
This issue was automatically closed due to inactivity.