Live queries let you subscribe to changes on a table and receive events in real time. They require the [WebSocket client](/docs/languages/swift/concepts/connecting#websocket-client) and are delivered as an `AsyncStream>`.
Starting a live query
let client = try SurrealWebSocketClient(endpoint: "ws://localhost:8000")
try await client.connect()
_ = try await client.signin(.root(username: "root", password: "root"))
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")
}
}Killing a live query
To stop receiving events, kill the live query using its id:
try await client.kill(liveQueryID: event.queryID)