• Start

Languages

/

Kotlin

/

Concepts

Live queries

Subscribe to real-time changes with live queries in the SurrealDB Kotlin SDK.

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.

MethodDescription
client.live(table)Starts a live query and returns a subscription
subscription.eventsA Flow of live notifications
subscription.cancel()Stops the subscription
client.kill(id)Kills a live query by ID

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)

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

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

Was this page helpful?