From 41b784370018a3642792a19c00c2b633c31604ac Mon Sep 17 00:00:00 2001 From: mnbjhu Date: Tue, 5 Sep 2023 13:41:54 +0100 Subject: [PATCH] Adding live queries section --- readme.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/readme.md b/readme.md index 1c421e5..0175889 100644 --- a/readme.md +++ b/readme.md @@ -156,6 +156,41 @@ assert(author.username == "John") assert(author.password == "1234") ``` +Live Queries + +Basic Usage: +```kotlin +// You can listen to changes in a table using the observeLiveQuery function +val incoming: LiveQueryFlow = db.observeLiveQuery("user") +// Each frame contains the type of change and the updated record +incoming.collect { frame -> + when (frame) { + is LiveQueryAction.Create -> { + println("New record created") + } + is LiveQueryAction.Update -> { + println("Record updated") + } + is LiveQueryAction.Delete -> { + println("Record deleted") + } + } +} +// LiveQueryFlow implements to Closeable interface +incoming.close() +``` + +For more control you can use the regular query method and subscribe to updates manually: +```kotlin +val result = db.query( + "LIVE SELECT * FROM user WHERE username = \$username", + bind("username", "John") +) +val liveQueryId = result.first().data() +val incoming = db.subscribe(liveQueryId) +db.kill(liveQueryId) +db.unsubscribe(liveQueryId) +``` ## Links - [SurrealDB](https://surrealdb.com/) - [Api Documentation](https://mnbjhu.github.io/surrealdb-kotlin-driver/api/)