Rospy subscriber needs sleep (some time) until the first message is received
Hi guys, I noticed following somehow strange behaviour. A topic subscriber is not ready to receive messages directly after its creation and needs some time until the first message can be received. The minimal example below illustrates this.
import rospy
from std_msgs.msg import String
def callback(data):
rospy.loginfo("I heard %s",data.data)
rospy.init_node('node_name')
pub = rospy.Publisher('topic_name', String, queue_size=10)
sub = rospy.Subscriber("topic_name", String, callback)
pub.publish("no delay")
rospy.sleep(1)
pub.publish("with delay")
rospy.spin()
Results in:
[INFO] [1483456752.613187]: I heard with delay
I would expect:
[INFO] [1483457135.695501]: I heard no delay
[INFO] [1483457135.696547]: I heard with delay
Is this behaviour correct, as it is somehow understandable that it needs time to initialize the callback thread for the subscriber, or is it actually a bug? Does exist a better way to solve this issue instead of using rospy.sleep?
It's the normal behaviour. You can check for a listener with getNumSubscribers/Publishers. Could you also have a look at latched topics.
Thank you for the valuable hint! I answered below.