I kind of faced a similar dilemma recently (but with the publisher and with Python).
It's probably not an ideal way to do it, but I introduced a boolean variable in the class that triggers the various functions inside the callback.
For a simple python
example which can also be implemented in cpp
Note: This code is purely for the logic and is not been tested.
class MyNode(Node)
def __init__(self):
super().__init__('my_node'):
self.cli = self.create_client(SetBool, 'on_off')
self.subscription = self.create_subscription(Joy, 'topic', self.listener_callback, 10)
self._future = None
self._sub = True
self.req = SetBool.Request()
self.subscription
def send_request(self):
self._sub = False
self.req.data = True
self._future = self.cli.call_async(self.req)
self._future.add_done_callback(self._cont_sub)
def _cont_sub(self):
ret = self._future.result()
if ret.success == True:
self.get_logger.info('service call success')
self._sub = True
else:
self.get_logger.info('service call failed')
self._future = None
def listener_callback(self, msg):
if self._sub:
self.get_logger.info('listener reading msg')
if msg.buttons[idx] == 'something':
self.send_request()
else:
self.get_logger.info('listener not reading msg')