LiveStream
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.
Method Syntax
stream.next()
Returns: Optional<LiveNotification>
Example
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.
Method Syntax
stream.close()
Returns: void
Example
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.
Method Syntax
notification.getAction()
Returns: String — one of "CREATE", "UPDATE", or "DELETE"
Example
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.
Method Syntax
notification.getValue()
Returns: Value (may be null for DELETE actions)
Example
Value record = notification.getValue();
.getQueryId()
Returns the UUID of the live query that produced this notification.
Method Syntax
notification.getQueryId()
Returns: String
Example
String queryId = notification.getQueryId();
Complete Example
Listening for live changes
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