The LiveStream class provides a blocking interface for receiving real-time notifications from live queries. It implements AutoCloseable, so it can be used in a try-with-resources block. Live streams are created by calling .selectLive() on a Surreal instance.
Live queries require a WebSocket connection (ws:// or wss://).
Source: surrealdb.java
Methods
.next()
Blocks until the next live query notification is available and returns it. Returns an empty Optional if the stream has been closed.
stream.next()**Returns:** `Optional`
LiveStream stream = db.selectLive("person");
Optional<LiveNotification> notification = stream.next(); .close()
Closes the live query subscription and releases associated resources. This is called automatically when using try-with-resources.
stream.close()Returns: void
stream.close(); LiveNotification
The LiveNotification class represents a single real-time notification received from a live query. Each notification contains the action that triggered it, the affected record value, and the live query identifier.
Methods
.getAction()
Returns the type of action that triggered the notification.
notification.getAction()Returns: String — one of "CREATE", "UPDATE", or "DELETE"
String action = notification.getAction(); .getValue()
Returns the record value associated with the notification. For CREATE and UPDATE actions, this is the full record. For DELETE actions, this may be null.
notification.getValue()Returns: Value (may be null for DELETE actions)
Value record = notification.getValue(); .getQueryId()
Returns the UUID of the live query that produced this notification.
notification.getQueryId()Returns: String
String queryId = notification.getQueryId();Complete example
import com.surrealdb.Surreal;
import com.surrealdb.LiveStream;
import com.surrealdb.LiveNotification;
import com.surrealdb.signin.RootCredential;
try (Surreal db = new Surreal()) {
db.connect("ws://localhost:8000");
db.useNs("surrealdb").useDb("docs");
db.signin(new RootCredential("root", "root"));
try (LiveStream stream = db.selectLive("person")) {
while (true) {
Optional<LiveNotification> notification = stream.next();
if (notification.isEmpty()) break;
LiveNotification n = notification.get();
System.out.println(n.getAction() + ": " + n.getValue());
}
}
}See also
Surreal — Connection and method reference
Live queries — Live query concepts and patterns
SurrealQL LIVE SELECT — Live query syntax