Why use subscribe?

  • I have a question about the subscribe method.


    I am building a sample that receives events and the add_event_callback method has the option of subscribing to the topic. So why would I ever need to use subscribe?


    The subscribe method has the following code as an example


    Python
    1. dxl_client.add_event_callback("/testeventtopic", MyEventCallback(), False)
    2. dxl_client.subscribe("/testeventtopic")



    The text says "By default when registering an event callback the client will automatically subscribe to the topic. In this example the dxlclient.client.DxlClient.add_event_callback() method is invoked with the subscribe_to_topic parameter set to False preventing the automatic subscription."


    If the add event callback does this why do I need subscribe?

  • It is correct that calling dxlclient.client.DxlClient.add_event_callback() with subscribe_to_topic set to True or leaving it to the default value (also True) will automatically subscribe the DxlClient to the specified topic in the topic parameter. This means that there is no need for your client code to subscribe to the topic as an additional step.


    The sample code for dxlclient.client.DxlClient.subscribe() specifically sets the subscribe_to_topic parameter of add_event_callback() to False to prevent the automatic subscription, and justify the usage of separately calling subscribe() for the code example.


    As for why you would ever want to call subscribe() yourself, that depends on the specific needs of your client.

    • If a client has a reason to set subscribe_to_topic as False, such as avoiding duplicate subscriptions by the same client. For example, using subscribe() to subscribe to a set of topics using a wildcard, and then assigning callbacks to specific topics that would be included in that set later - in that case, it would be better to call add_event_callback() with subscribe_to_topic set to False.
    • If a client calls dxlclient.client.DxlClient.unsubscribe() for a topic, then there may be a need to re-subscribe later.