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
Method | Description |
|---|---|
db.selectLive(table) | Starts a live query on a table |
stream.next() | Returns the next notification |
stream.close() | Closes the live query |
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()`](/docs/reference/java/api/core/live-stream#next) on the `LiveStream` to block until the next notification arrives. It returns an `Optional` — the optional is empty if the stream has been closed.
Each LiveNotification provides:
.getAction()— the type of change:CREATE,UPDATE, orDELETE.getValue()— the record data as aValue.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
Surreal API reference for the selectLive method
LiveStream API reference for stream and notification details
Connecting to SurrealDB for WebSocket connection setup
SurrealQL LIVE SELECT for the underlying query syntax
DEFINE TABLE ... CHANGEFEED for configuring changefeeds on tables