getNumSubscribers invalid return value if no publishing

asked 2020-01-27 10:19:12 -0600

Pashek gravatar image

updated 2020-01-27 10:22:38 -0600

ros::Publisher::getNumSubscribers() doesn't react on unsubscribing if nothing is being published on the topic.

Steps (in C++):

  • Create your publisher with

    pub = nh.advertise<anymsgtype>("some_topic", 1)

  • Don't publish anything on the topic but continuously monitor the number of subscribers with, say

    ROS_INFO("# of subscribers: %i", pub.getNumSubscribers())

  • Subscribe to the topic "some_topic" with, say, rostopic echo. Open terminal and run

    rostopic echo some_topic

    The value returned by getNumSubscribers will increase by 1.

  • Unsubscribe from the topic by Ctrl-C in the terminal with rostopic echo .

    The value returned by getNumSubscribers will remain to be 1.

    Disconnect callback (if specified during the publisher creation) isn't called.

After every subscribe\unsubscribe cycle the number returned by getNumSubscribers will increase by 1.

Is this correct behaviour? My use-case is to publish only if there are subscribers, and if some other independent conditions met which may prevent it from being published.

I'm using ROS Melodic on Ubuntu 18.04, kernel 4.18, x86.

edit retag flag offensive close merge delete