ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Can a topic be subscribed in two different function of the same program

asked 2018-08-29 23:23:55 -0500

rama_bhuyan gravatar image

I wanted to subscribe same topic in two different functions of the same code. so I just wanted to know, will the subscriber stops subscribing after it comes out of the function or it still keeps on subscribing.

just the format I have followed,

finction_1()
   {
     ros::subscriber sub= n.subscribe("topic", 1000, topic_callback);
   }

finction_2()
   {
    ros::subscriber sub= n.subscribe("topic", 1000, topic_callback);
   }

int main ()
{
      function_1();
     function_2();
 }

will this format create any conflict?

edit retag flag offensive close merge delete

Comments

It might be helpful to know what you are planning to do. As ahendrix said, it's possible to create the subscribers inside the function but they will be destroyed right away. If you just need some data inside your function block, maybe have a look at ros::topic::waitForMessage.

pcoenen gravatar image pcoenen  ( 2018-08-30 03:39:41 -0500 )edit

I'm a little confused. Creating a subscriber sets up a callback function to be executed every time a message is received. Are you trying to subscribe two callbacks to the same topic or are you trying to subscribe and unsubscribe to the topic at different times within your node?

PeteBlackerThe3rd gravatar image PeteBlackerThe3rd  ( 2018-08-30 07:52:04 -0500 )edit

my query is, once the function scope is over the subscriber stops subscribing?

rama_bhuyan gravatar image rama_bhuyan  ( 2018-09-02 23:38:07 -0500 )edit

The way that you have written the code above, yes the subscriber stops subscribing when the function returns. However if the variable sub was global then it would keep subscribing after the function returns.

PeteBlackerThe3rd gravatar image PeteBlackerThe3rd  ( 2018-09-10 09:13:34 -0500 )edit

yes, it is global variable. And it keep on subscribing after the function returns. but I have resolved the issue of multiple subscription.

thank you

rama_bhuyan gravatar image rama_bhuyan  ( 2018-09-11 07:10:26 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2018-08-30 01:59:44 -0500

ahendrix gravatar image

I don't think there are any issues with having multiple subscribers on the same topic.

I do see another problem with your code; your functions create a subscriber, but as soon as the function is over, the subscriber object is destructed and that subscriber stops. If you want the subscriber to continue working, you need to keep the subscriber object (or a copy of it).

edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2018-08-29 23:23:55 -0500

Seen: 261 times

Last updated: Aug 30 '18