Skip to content

Concepts

Live queries

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

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)
ArgumentDescription
query (required)A live query built with SurrealDSL.live(_:) or the #live macro.
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))

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

Kills a running live query by its id, ending the associated AsyncStream.

Method Syntax
try await client.kill(liveQueryID: id)
ArgumentDescription
liveQueryID (required)The id of the live query to kill, available as event.queryID on received events.
try await client.kill(liveQueryID: event.queryID)

Was this page helpful?

Last updated