惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

aimingoo的专栏
aimingoo的专栏
腾讯CDC
Y
Y Combinator Blog
L
LangChain Blog
B
Blog
U
Unit 42
P
Proofpoint News Feed
G
Google Developers Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
WordPress大学
WordPress大学
月光博客
月光博客
Vercel News
Vercel News
雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 叶小钗

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop Losing Offline User Updates: Build a Room Mutation Q...
YADNYESH RANA · 2026-06-24 · via DEV Community

YADNYESH RANA

Most Android apps handle offline reads using Room as a cache. But when it comes to offline writes (mutations like updates, inserts, or deletes), standard implementations either fail immediately or block the UI until the network returns.

To build a true offline-first app, you need a local transaction write-queue.

Here is a lightweight, production-grade blueprint using Room, Ktor, and WorkManager to buffer and sync offline updates reliably.


1. The Offline Mutation Schema
First, create a SQLite table in Room to store pending mutations. This table captures the type of operation, the target table, and the serialized payload.

@Entity(tableName = "mutation_queue")
data class PendingMutation(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,
    val type: String,          // "INSERT", "UPDATE", "DELETE"
    val targetTable: String,   // e.g., "tasks", "users"
    val payloadJson: String,   // Serialized request body
    val timestamp: Long = System.currentTimeMillis()
)

Create the corresponding Data Access Object (DAO) to write, fetch, and clear queued operations:

@Dao
interface MutationDao {
    @Query("SELECT * FROM mutation_queue ORDER BY timestamp ASC")
    suspend fun getAllPending(): List<PendingMutation>

    @Delete
    suspend fun delete(mutation: PendingMutation)

    @Insert
    suspend fun insert(mutation: PendingMutation)
}


2. Writing to the Queue Natively
When a user performs an update while offline, write the data to the local feature table (so the UI updates immediately) and queue the transaction inside a single database transaction:

suspend fun updateTaskOffline(task: TaskEntity) {
    database.withTransaction {
        // 1. Update the local UI cache table
        taskDao.update(task)

        // 2. Queue the mutation for server sync
        val mutation = PendingMutation(
            type = "UPDATE",
            targetTable = "tasks",
            payloadJson = json.encodeToString(task)
        )
        mutationDao.insert(mutation)
    }
    // 3. Trigger WorkManager to run sync task
    scheduleSyncWorker()
}


3. The WorkManager Synchronization Loop
Now, write a CoroutineWorker that reads the queue and flushes the mutations to your API sequentially.

class SyncWorker(
    context: Context,
    params: WorkerParameters,
    private val db: AppDatabase,
    private val api: KtorClient
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        val pendingMutations = db.mutationDao().getAllPending()
        if (pendingMutations.isEmpty()) return Result.success()

        for (mutation in pendingMutations) {
            try {
                // Post payload to Ktor server
                val response = api.post("api/sync") {
                    setBody(mutation.payloadJson)
                }

                // If success, delete from queue
                if (response.status.value in 200..299) {
                    db.mutationDao().delete(mutation)
                }
            } catch (e: Exception) {
                // If API fails or times out, reschedule with exponential backoff
                return Result.retry()
            }
        }
        return Result.success()
    }
}


4. Scheduling the Sync
Set up constraints to ensure the worker only runs when the device has an active network connection, and apply an exponential backoff policy:

fun Context.scheduleSyncWorker() {
    val constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.CONNECTED)
        .build()

    val syncWorkRequest = OneTimeWorkRequestBuilder<SyncWorker>()
        .setConstraints(constraints)
        .setBackoffCriteria(
            BackoffPolicy.EXPONENTIAL,
            10,
            TimeUnit.SECONDS
        )
        .build()

    WorkManager.getInstance(this).enqueueUniqueWork(
        "OfflineSyncWork",
        ExistingWorkPolicy.KEEP, // Keep existing sync task in queue, don't interrupt
        syncWorkRequest
    )
}


The Result

  1. The user updates data offline.
  2. The UI changes immediately (caching).
  3. The mutation is saved in Room.
  4. WorkManager triggers the moment connection returns, uploading the queue chronologically without user intervention.

Open-Source Reference
This implementation is part of the open-source Android System Design & Architecture Checklist. You can clone the full repository of offline-first configurations, convention plugins, and secure Keystore setups here:

👉 GitHub: Android System Design & Architecture Checklist (A print-ready, high-resolution 12-page PDF version is also pinned in the repository description).