Live queries push changes to your application as records are created, updated, or deleted. In the Kotlin SDK, a live subscription exposes a coroutine Flow of notifications that you collect.
Live queries require a stateful connection and are only available over the WebSocket transport. Calling .live() over HTTP throws SurrealFeatureNotSupportedException. Check support with client.supports(SurrealFeature.LiveQueries).
API references
Method | Description |
|---|---|
client.live(table) | Starts a live query and returns a subscription |
subscription.events | A Flowof live notifications |
subscription.cancel() | Stops the subscription |
client.kill(id) | Kills a live query by ID |
Starting a live query
Call .live() with a table name to receive a LiveQuerySubscription, then collect its events flow. Each SurrealLiveNotification carries an action ("CREATE", "UPDATE", or "DELETE") and a result payload.
import com.surrealdb.kotlin.SurrealFeature
import kotlinx.coroutines.launch
if (client.supports(SurrealFeature.LiveQueries)) {
val subscription = client.live("person")
val job = scope.launch {
subscription.events.collect { event ->
println("${event.action}: ${event.result}")
}
}
}Pass diff = true to receive JSON Patch diffs instead of the full record.
val subscription = client.live("person", diff = true)Filtered live queries
To watch a subset of records with a WHERE clause, run a LIVE SELECT statement through .query(); the result is the live query UUID, which you can later pass to .kill().
val liveId = client.query("LIVE SELECT * FROM person WHERE age >= 18")Stopping a subscription
Cancel a subscription started with .live() by calling .cancel(), which also kills the underlying live query on the server. Cancel the collecting coroutine separately.
subscription.cancel()
job.cancel()For live queries started via raw SurrealQL, kill them with their UUID.
client.kill(liveId.toString())Learn more
Live subscription reference for the subscription and notification types
SurrealClient API reference for
.live()and.kill()Features and events for checking transport support
LIVE SELECT for the SurrealQL statement