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 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)
See the live and kill method references for more detail.