Zenoh provides two ways to receive sequential data (Samples or Replies):
Channels (Iterative)
By providing a channel type (like zenoh.handlers.FifoChannel or zenoh.handlers.RingChannel) to the handler parameter, the returned object becomes an iterable.
- Use
for item in subscriber: to receive data. - Use
subscriber.recv() for blocking receive or subscriber.try_recv() for non-blocking. - The subscriber is automatically undeclared when the object goes out of scope.
Callbacks (Background Mode)
Pass a callable to the handler parameter. The subscriber/queryable runs in background mode and remains active even if the returned object goes out of scope.
CAUTION: Do not call Zenoh API functions or perform blocking operations inside a callback. This is unsafe and can lead to deadlocks or crashes.
import zenoh
from zenoh.handlers import FifoChannel
# Channel approach
with zenoh.open() as session:
sub = session.declare_subscriber("key", handler=FifoChannel())
for sample in sub:
print(sample.payload)
# Callback approach
def my_callback(sample):
print(f"Received {sample.payload}")
with zenoh.open() as session:
# This stays active in the background
session.declare_subscriber("key", handler=my_callback)