0
$\begingroup$

Rosanswers logo

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)

Originally posted by knxa on ROS Answers with karma: 811 on 2023-05-10

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

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)

Originally posted by bluegiraffe-sc with karma: 221 on 2023-05-19

This answer was ACCEPTED on the original site

Post score: 2

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.