Live queries let you subscribe to changes on a table and receive events in real time. They require the WebSocket client and are delivered as an AsyncStream<LiveEvent<T>>.
Method | Description |
|---|---|
client.live(query) | Subscribes to changes via a live query (WebSocket only) |
client.kill(liveQueryID) | Kills a running live query |
.live()
Subscribes to changes on a table and returns an AsyncStream<LiveEvent<T>> of events.
Important
Live queries require the WebSocket client. The HTTP client does not support them.
Method Syntax
try await client.live(query)Arguments
| Argument | Description |
|---|---|
query (required) | A live query built with SurrealDSL.live(_:) or the #live macro. |
Example usage
let client = try SurrealWebSocketClient(endpoint: "ws://localhost:8000")
try await client.connect()
_ = try await client.signin(.root(username: "root", password: "secret"))
try await client.use(namespace: "myapp", database: "mydb")
let stream = try await client.live(SurrealDSL.live(Person.self))Consuming events
Iterate the stream with for await and switch on the event's action:
for await event in stream {
switch event.action {
case .create:
print("Created:", event.decoded as Any)
case .update:
print("Updated:", event.decoded as Any)
case .delete:
print("Deleted record:", event.recordID)
case .killed:
print("Live query was killed")
}
} .kill()
Kills a running live query by its id, ending the associated AsyncStream.
Method Syntax
try await client.kill(liveQueryID: id)Arguments
| Argument | Description |
|---|---|
liveQueryID (required) | The id of the live query to kill, available as event.queryID on received events. |
Example usage
try await client.kill(liveQueryID: event.queryID)