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

How does the latch work in advertise function ?

asked 2020-09-02 20:28:42 -0600

rjosodtssp gravatar image

I already read this link:

But I still don't get it, I didn't find any difference whether latch=true or false, the answer is add ros::spin in code, but I thought that's used for subscriber.

this is my main()

ros::init(argc,argv, "Pub");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<std_msgs::Int8>("topic", 50, true);
ros::Rate rate(1);

std_msgs::Int8 msg; = 0;

return 0;
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-09-03 02:15:01 -0600

Delb gravatar image

From the wiki :

latch [optional]

Enables "latching" on a connection. When a connection is latched, the last message published is saved and automatically sent to any future subscribers that connect. This is useful for slow-changing to static data like a map. Note that if there are multiple publishers on the same topic, instantiated in the same node, then only the last published message from that node will be sent, as opposed to the last published message from each publisher on that single topic.

That means that if you publish a message with latch=true then every subscriber will get the message once even if you don't publish it anymore. Your code is publishing in a while loop so indeed it won't make a difference wether latch=true or false because you always send a new message. To show the difference you need to publish data only once (or several time but stop at some point) and then subscribe to the topic when it's not published anymore (with rostopic echo for example). A code that would show the difference could be :

ros::init(argc,argv, "Pub");
ros::NodeHandle nh;
ros::Publisher pub_latch_true = nh.advertise<std_msgs::Int8>("topic_latch_true", 50, true);
ros::Publisher pub_latch_false = nh.advertise<std_msgs::Int8>("topic_latch_false", 50, false);
ros::Rate rate(1);

std_msgs::Int8 msg; = 2;
return 0;

Run this node (the while loop is only to keep the node alive) and then do rostopic echo /topic_latch_true and rostopic echo /topic_latch_false, you won't have any output for topic_latch_false and you will have only one message with topic_latch_true (the last published message).

edit flag offensive delete link more


thank you, very helpful

rjosodtssp gravatar image rjosodtssp  ( 2020-09-03 05:49:31 -0600 )edit

Question Tools



Asked: 2020-09-02 20:28:42 -0600

Seen: 1,537 times

Last updated: Sep 03 '20