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

rospy and Subscriber/Publisher garbage collection

asked 2023-05-10 03:54:59 -0500

knxa gravatar image

Do I need to store a reference to rospy subscribers and publishers to avoid these objects to be garbage collected?

class SomeClass:
    def __init__(self):

        # option 1, without reference
        rospy.Subscriber("/some/topic1", SomeMessageType, self.some_topic1_callback)

        # option 2, with reference
        self.my_subscriber = rospy.Subscriber("/some/topic2", SomeMessageType, self.some_topic2_callback)
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-19 05:27:26 -0500

bluegiraffe-sc gravatar image

It is not necessary to store a reference to a Subscriber (but you can!). It will keep working even after that the __init__ has been completed (of course as long as an instance of SomeClass is defined and the node is running).

As for the Publisher, in general, yes you should store a reference to it. In this way, you can publish also from outside the function in which you have defined it.

I hope that this example can help you:

class SomeClass:
    def __init__(self):

        # Defined Subscriber without reference
        rospy.Subscriber("/some/topic1", SomeMessageType, self.some_topic1_callback)

        # Defined Publisher with reference
        self.my_pub = rospy.Publisher("/some/topic2", SomeMessageType, queue_size=1)


    def some_topic1_callback(self, msg):

        # Do something with your message
        new_msg = self.great_function_doing_stuff(msg)

        # Publish the result
        self.my_pub.publish(new_msg)
edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2023-05-10 03:54:59 -0500

Seen: 121 times

Last updated: May 19 '23