Live queries
The Java SDK supports real-time live queries that stream changes from the database to your application. When records in a table are created, updated, or deleted, the SDK delivers notifications through a LiveStream that you can consume in a loop or process asynchronously.
API References
Starting a live query
The .selectLive() method subscribes to changes on a table and returns a LiveStream. Live queries require a WebSocket connection (ws:// or wss://) because the server pushes notifications over the persistent connection.
try (Surreal db = new Surreal()) {
db.connect("ws://localhost:8000");
db.useNs("surrealdb").useDb("docs");
db.signin(new RootCredential("root", "root"));
LiveStream stream = db.selectLive("users");
}
Receiving notifications
Call .next() on the LiveStream to block until the next notification arrives. It returns an Optional<LiveNotification> — the optional is empty if the stream has been closed.
Each LiveNotification provides:
.getAction() — the type of change: CREATE, UPDATE, or DELETE.getValue() — the record data as a Value.getQueryId() — the unique identifier of the live query
LiveStream stream = db.selectLive("users");
while (true) {
Optional<LiveNotification> notification = stream.next();
if (notification.isEmpty()) break;
LiveNotification n = notification.get();
System.out.println(n.getAction() + ": " + n.getValue());
}
Closing a live query
Call .close() to unsubscribe from the live query and release the server-side subscription. LiveStream implements AutoCloseable, so you can use try-with-resources to ensure the stream is closed automatically.
try (LiveStream stream = db.selectLive("users")) {
Optional<LiveNotification> notification = stream.next();
notification.ifPresent(n ->
System.out.println(n.getAction() + ": " + n.getValue())
);
}
Learn more