Package io.zenoh.pubsub
Class Subscriber
-
- All Implemented Interfaces:
-
io.zenoh.session.SessionDeclaration,java.lang.AutoCloseable
public class Subscriber implements AutoCloseable, SessionDeclaration
A subscriber that allows listening to updates on a key expression and reacting to changes.
Its main purpose is to keep the subscription active as long as it exists.
The declaring session holds a strong reference to it: dropping your own reference does NOT stop the subscription — it stays active until close (or
undeclare) is called or the session is closed, whichever comes first. Only after that does it become eligible for garbage collection.Example using the default BlockingQueueHandler handler:
var queue = session.declareSubscriber("a/b/c"); try (Session session = Zenoh.open(config)) { try (var subscriber = session.declareSubscriber(keyExpr)) { var receiver = subscriber.getReceiver(); assert receiver != null; while (true) { Optional<Sample> wrapper = receiver.take(); if (wrapper.isEmpty()) { break; } System.out.println(wrapper.get()); } } }Example using a callback:
try (Session session = Zenoh.open(config)) { session.declareSubscriber(keyExpr, System.out::println); }Example using a handler:
class MyHandler implements Handler<Sample, ArrayList<Sample>> {...} //... try (Session session = Zenoh.open(config)) { var handler = new MyHandler(); var arraylist = session.declareSubscriber(keyExpr, handler); // ... }