Skip to content

Creating Subscriptions

ds58 edited this page Jul 16, 2025 · 6 revisions

Subscriptions allow you to receive data from Publishers on the same topic and domain ID.

Creating a ROS2Subscription

Creating a ROS2Subscription requires a ROS2Node and ROS2Topic. The subscription is typed with the message type of the ROS2Topic.

The two types of subscriptions

Type 1 (using ROS2SubscriptionCallback)

This is the default approach for creating subscriptions. You are given full control of the message allocation and reading the message from the underlying buffer into a Java object (de-serialization of the message).

ROS2Node node = new ROS2Node("my_node");
ROS2Topic<Int32> topic = new ROS2Topic("/my_topic", Int32.class);

node.createSubscription(topic, reader -> {
  // Subscription callback (this runs when the subscription receives a message)

  // There are 2 read() methods.
  // read() with no args allocates a new message Java object and de-serializes the buffer into the message object.
  // read(T) takes a T message type class and de-serializes the buffer into it. This allows you to reuse a message object if you store it as a field, for example.

  Int32 msg = reader.read();
  System.out.println(msg);
});

Type 2 (using ROS2SubscriptionCallbackSampler)

This is the shorthand way for creating subscriptions. In the callback, it gives you the already de-serialized instance of the message. Call this approach a 'subscription sampler,' or simply a 'sampler.'

Internally, this approach uses the Type 1 createSubscription() and manages a single instance of the message type class and a ROS2SubscriptionCallback.

This method is always allocation-free. It reuses the same Java object for the message sample each time it receives a message.

[...]
node.createSubscriptionSampler(topic, msg -> {
  // Subscription callback (this runs when the subscription receives a message)
  // Do whatever you want with the msg

  System.out.println(msg);
});

Clone this wiki locally