• Start

Languages

/

Swift

/

Concepts

Live queries

Subscribe to real-time data changes using live queries and AsyncStream in the SurrealDB Swift SDK.

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>>.

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))

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")
}
}

To stop receiving events, kill the live query using its id:

try await client.kill(liveQueryID: event.queryID)

See the live and kill method references for more detail.

Was this page helpful?