Skip to content

Quickstart: sync an Android app with Kovlet

Add live sync that works offline to an Android app with com.kovlet:kovlet-android. People sign in once, and your @Serializable rows stay in sync with every other app on the same Data Space, through Kotlin Flows.

5 min readUpdated December 2026Markdown
On this page

What you'll build

  • An Android todo app whose rows sync with every other app on the same Data Space.
  • Sign-in once, with a short code or a browser tab. The app then finds or creates its space on its own.
  • Writes land on the device at once and sync in the background, offline too.
  • Optional extras: files, live queries, all-or-nothing writes, and sign-in for people without a Kovlet account.

Prerequisites

You need a Kovlet server. Pick one:

  • The hosted API at https://api.kovlet.com. The free plan is enough for testing. You sign in on the console at https://kovlet.com.
  • A local kovletd --dev, from the ghcr.io/kovlethq/kovletd Docker image or the kovletd binary. Run Kovlet locally starts it and shows how to approve your app from the terminal.

Step 1: Install

Add com.kovlet:kovlet-android from Maven Central. You also need the Kotlin serialization plugin, because rows are @Serializable data classes:

app/build.gradle.kts
plugins {
    id("org.jetbrains.kotlin.plugin.serialization")
}

android {
    defaultConfig {
        ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
    }
}

dependencies {
    implementation("com.kovlet:kovlet-android:0.1.0")
}

The library needs minSdk 26 (Android 8.0) or later. The AAR carries the native core for arm64-v8a, armeabi-v7a and x86_64.

By default, the client talks to https://api.kovlet.com and opens sign-in and consent on https://kovlet.com.

Step 2: Sign in

TodosModel.kt
val kovlet = Kovlet.client(app, appName = "Todos")
if (!kovlet.isSignedIn) kovlet.signIn(SignIn.device { message.value = "Approve ${it.userCode} at ${it.verificationUri}" })

Kovlet.client(context, appName = ...) creates the client. SignIn.device { ... } uses the device flow: the app shows a short code, and the person approves it in any browser.

For a one-tap browser sign-in, use SignIn.customTab(...) instead. It runs PKCE, the standard browser sign-in for apps, in a Custom Tab with a reverse-DNS redirect scheme:

Kotlin
kovlet.signIn(SignIn.customTab(activity, redirect = "com.example.todos:/kovlet/callback"))

Then route that scheme to the library's redirect activity:

AndroidManifest.xml
<activity
    android:name="com.kovlet.KovletRedirectActivity"
    android:exported="true"
    android:theme="@android:style/Theme.Translucent.NoTitleBar">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="com.example.todos" />
    </intent-filter>
</activity>

Closing the tab without approving throws KovletException with code sign_in_cancelled.

Sign in once. The app stays signed in across restarts.

  • The device keyA key pair the app creates and can't export. It binds a session to one device. is an Android Keystore EC P-256 key (StrongBox when available).
  • The session tokens refresh themselves and are Keystore-encrypted.
  • Check isSignedIn before calling signIn.

Step 3: Pick or create a space

A Data SpaceA set of typed tables plus a tree of files, shared by every app with access to it. holds your tables and files. This line finds the space named "Todos", or creates it:

Kotlin
val spaceId = kovlet.spaces.findOrCreate("Todos").id
  • spaces.list() returns the spaces the person granted this app.
  • spaces.create(name, slug) makes a new one.
  • Neither needs the console or another sign-in.

Step 4: Sync a table

Open the space with your tables, then read and write typed rows:

TodosModel.kt
@Serializable
data class Todo(val id: String, val title: String = "", val done: Boolean = false)

val space = kovlet.open(spaceId, listOf(Table("todos", "title" to ColumnType.STRING, "done" to ColumnType.BOOLEAN)))
val todos = space.table<Todo>("todos")

viewModelScope.launch { todos.observe().collect { list -> state.value = list } }
todos.upsert(Todo(id = UUID.randomUUID().toString(), title = "Buy milk"))
  • open(...) declares the tables.
  • space.table<Todo>("todos").observe() is a Flow<List<Todo>>.
  • upsert writes locally and syncs.

You should see

  • The device code message ("Approve ABCD-EFGH at https://kovlet.com/activate") on the first launch.
  • Once you approve it, state holds "Buy milk" at once.
  • Then every row other apps wrote to the same Todos space, such as the ones from the web or Node quickstart.
  • Later launches skip sign-in.

How reads and writes work

  • Writes go to the built-in local store first, then sync in the background.
  • upsert(id, fields) writes a JsonObject patch.
  • all(), get(id), delete(id) and restore(id) do what they say.
  • Fields merge per field, and the later write wins.
  • Column types: ColumnType.STRING, NUMBER, BOOLEAN, DATETIME, JSON, FILE_REF, ColumnType.ref("table"), each with .optional(). New tables and optional columns are created on open.
  • To keep your own database (Room, SQLite) as the source of truth, pass store = to open with a KovletDataStore. Its apply(batch: ChangeBatch) receives each merged batch in order.

Step 5: FilesOptional

Kotlin
val f = space.files.put("photos/receipt.jpg", jpegBytes, "image/jpeg")
todos.upsert(todoId, buildJsonObject { put("photo", f.id) })      // a FILE_REF column
space.files.download(f.id, File(context.cacheDir, "receipt.jpg"))  // suspend; checks the SHA-256
  • Uploads are staged and sent in the background, so they work offline.
  • files.put(path, file, mimeType) streams from a File.
  • files.list(prefix), move and delete cover the rest.

Step 6: Status and lifecycleOptional

Kotlin
Kovlet.observeLifecycle()                                         // pause in the background, resume in the foreground
lifecycleScope.launch { kovlet.status.collect { showSync(it.state, it.pending) } }   // StateFlow<Status>
  • kovlet.events is a SharedFlow of rejected writes, errors and quota warnings.
  • For background catch-up, subclass KovletSyncWorker and call KovletSyncWorker.schedule<YourWorker>(context). It needs androidx.work:work-runtime-ktx.

Step 7: Live queriesOptional

A live query keeps a result up to date as data changes. The client speaks sync protocol 2, where one socket per space carries many subscriptions.

A query is a JSON tree, like InstaQL:

  • Top-level keys are tables.
  • Nested keys follow ref columns, forward or backward.
  • $ holds where, order, limit and fields.

The query language reference has the details.

Kotlin
val open = space.subscribe(buildJsonObject {
    putJsonObject("todos") {
        putJsonObject("
quot;
) { putJsonObject("where") { put("done", false) }; put("limit", 50) }
putJsonObject("owner") {} // follow the ref column } }) viewModelScope.launch { open.results().collect { r -> state.value = r.data["todos"].orEmpty() } }
  • Full or partial copy. open(...) keeps a full replica and runs queries locally. openQuery(...) keeps a partial replica: the server sends only the rows your subscriptions match. A row no subscription holds any more leaves the store (a purge change for your own KovletDataStore).
  • Restarts. Subscriptions survive restarts and resume from their last cursor.
  • Status. open.unsubscribe() ends one. open.status shows complete, more and errors such as invalid_query.
  • One-off queries. space.query(q) runs a query once over the local store, offline too, with the same matcher as the server. space.queryRemote(q) asks the server.

Step 8: Atomic writesOptional

space.transact(writes) writes several rows all or nothing:

Kotlin
val tx = space.transact(listOf(
    Write.Upsert("teams", teamId, buildJsonObject { put("name", "Core") }),
    Write.Upsert("members", memberId, buildJsonObject { put("team", teamId); put("role", "owner") }),
))
tx.settled()       // "applied", or throws the rejection
  • The writes apply locally at once and go to the server as one batch. The server applies all of them or none.
  • If it rejects the batch, every write rolls back together.
  • Queued writes to rows the batch created roll back too (dependency_rejected).
  • kovlet.events emits Event.Transaction(status = "rejected", ...).

Step 9: End users (public apps)Optional

A public app can sign people in without a Kovlet account. These people are end users. They can sign in with an email code, OAuth, an ID token or as a guest. A space owner turns end-user sign-in on for your app in the console. appId is your app's public ID.

Kotlin
val auth = kovlet.endUsers(spaceId, appId = "app_…")
auth.sendMagicCode(email)
auth.signInWithMagicCode(email, code)                 // or signInAsGuest(), signInWithIdToken(provider, token)
// auth.signInWithOAuth(activity, provider = "google", redirect = "com.example.todos:/oauth")

val space = kovlet.openQuery(spaceId, tables)
val mine = space.subscribe(buildJsonObject { putJsonObject("todos") {} })   // only rows the rules let them view

How end-user sessions behave:

  • The session is bound to the Keystore device key and refreshes by itself.
  • OAuth reuses the Custom Tab and KovletRedirectActivity from step 2, so register the redirect URI for your app.
  • End users always sync over protocol 2 with query subscriptions.
  • The space's rules decide which rows arrive and which writes are accepted.
  • auth.signOut() (or kovlet.signOut()) forgets every open space's synced rows and queued writes, so the next person on the device starts clean.

Local development

Run Kovlet locally starts kovletd --dev with Docker or the kovletd binary.

terminal
kovletd --dev --dev-auto-approve     # http://127.0.0.1:8080, approves device codes at once
Kotlin
val kovlet = Kovlet.client(app, appName = "Todos", baseUrl = "http://10.0.2.2:8080")   // the host, seen from the emulator

On a physical device, run adb reverse tcp:8080 tcp:8080 and use http://127.0.0.1:8080. Allow cleartext HTTP for that host in a debug network security config.

Without the SDK

An Android app can also talk to Kovlet directly with OkHttp or Ktor, without the library. It uses device-code sign-in, REST for spaces and reads, and a WebSocket for writes and live sync. Start with the REST + WebSocket quickstart. The sync protocol reference covers every frame, merge rule and error.

Next

Ready to try it? Start free. No credit card, no API keys.

For coding agents: this page is also Markdown. Add .md to the URL or send Accept: text/markdown. The full reference is at /llms-full.txt.