我在 paho_mqtt 开始 loop_forever() 后可以订阅主题吗?

Can i subscribe to a topic after i started loop_forever() in paho_mqtt?

在执行 loop_forever() 函数之前,我是否需要订阅所有我感兴趣的主题?例如。在 MQTT 客户端的生命周期内以某种方式动态添加更多订阅。

我发现这是可能的。我实现了一个 class 隐藏了 mqtt 的东西。在构造函数中,我连接到代理并使用单独的线程启动 loop_forever() 。然后 class 订阅了一些主题并为每个主题注册了一个回调,这些回调是从 on_message.

调用的
c = comm("localhost")
c.register_handler("topic1", first_handler)
c.register_handler("topic2", second_handler)

class comm:
    def __init__(self, broker_address):
        self.client = mqtt.Client("")
        self.client.on_message = self.on_message
        self.callbacks = dict()
        self.client.connect(broker_address)
        threading.Thread(target=self.__run, daemon=True).start()
        
    def __run(self):
        self.client.loop_forever()

    def on_message(self, client, userdata, msg):
        self.callbacks[msg.topic](jsonpickle.decode(msg.payload))

    def on_connect(self, client, userdata, flags, rc):
        for topic in self.callbacks:
           self.client.subscribe(topic)    

    def register_handler(self, topic: str, handler: Callable[[Dict], None]):
        self.callbacks[topic] = handler
        self.client.subscribe(topic)