Android
A Base Worker Template for Batched Room Inserts with Retry and Progress
Duplicating notification logic and batch-insert boilerplate across seven WorkManager workers is how bugs hide. This post covers an abstract base class that reduces each worker to three overrides while handling batching, retries, backup recovery, and progress notifications centrally.
- Published
- Reading
- 6 min
- Author
- Fidelis Uwem Joseph
Series · Part 4 of 8WorkManager in Production
- Injecting Dependencies into WorkManager Workers with Hilt
- WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
- Seeding a Room Database with a WorkManager Phased Dependency Graph
- A Base Worker Template for Batched Room Inserts with Retry and Progress
- Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
- Protecting Downloaded Files with a Rename-to-Backup Strategy
- Passing Structured Failure Data Out of a WorkManager Worker
- Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
When you have seven CoroutineWorker subclasses that all parse a JSON file
and insert rows into Room, the temptation is to copy-paste the batch loop,
the notification update, and the retry guard into each one. That pattern means
seven places to fix the next bug. The alternative is an abstract base class
where each concrete worker supplies a filename, a resource key, and a single
processFile implementation — everything else is inherited.
Prerequisites
Kotlin 2.0, WorkManager 2.11.1, Room 2.7.1, Hilt 2.56 with hilt-work for
@HiltWorker injection. Notification permission handling for Android 13+.
Background
The app seeds a local Room database from downloaded JSON files. There are seven entity types: colors, categories, parts, gear, minifigures, codes, and inventory. Each worker follows an identical pattern:
- Find the JSON file on external storage
- If missing, look for a
.bakbackup - Parse it and insert in batches of 1,000 rows
- Post progress notifications as batches complete
- Retry up to 3 times if the file is not yet present
Putting this logic in each worker individually means that when Room adds a new
onConflict strategy or the notification permission guard changes for Android
13+, you update seven files. The base class reduces that to one.
Implementation
1. The base class contract
The abstract class takes everything that changes between workers as constructor parameters (notification IDs, notification builders) and declares three abstract members that subclasses must implement.
abstract class BaseWriteToDatabase( context: Context, workParameters: WorkerParameters, private val notificationManager: NotificationManagerCompat, private val notificationBuilder: NotificationCompat.Builder, protected val progressRepository: ProgressRepository, private val notificationId: Int) : CoroutineWorker(context, workParameters) {
companion object { const val MAX_RETRY_ATTEMPTS = 3 const val BATCH_SIZE = 1_000 private const val BRICKWORK_DIR = "brickwork" }
abstract val fileName: String abstract val resourceKey: String protected abstract suspend fun processFile(jsonFile: File): Int}BATCH_SIZE = 1_000 is defined here, not in each subclass, so it applies
everywhere. If you ever need to reduce it for low-memory devices you change
one line.
2. The doWork() routing logic
doWork() handles three cases: main file present, main file missing but backup
present, neither present. The backup path exists because the file downloader
renames the previous file to .bak before writing the new one — if a download
is interrupted, the previous version is still usable.
override suspend fun doWork(): Result { val mainFile = brickworkFile(fileName) val backupFile = brickworkFile("$fileName.bak")
return try { when { mainFile.exists() -> processAndSucceed(mainFile) backupFile.exists() -> restoreFromBackup(backupFile, mainFile) else -> handleMissingFile() } } catch (e: CancellationException) { throw e // never swallow cancellation } catch (e: Exception) { Timber.e(e, "[$resourceKey] Unhandled error") Result.failure() }}
private fun handleMissingFile(): Result { Timber.w("[$resourceKey] No file or backup. Attempt ${runAttemptCount + 1}/${MAX_RETRY_ATTEMPTS + 1}") return if (runAttemptCount >= MAX_RETRY_ATTEMPTS) { Timber.e("[$resourceKey] Max retries reached — giving up") Result.failure() } else { Result.retry() }}runAttemptCount is provided by ListenableWorker and starts at 0, then
increments on each retry. No inputData keys needed — WorkManager owns this
counter. With MAX_RETRY_ATTEMPTS = 3 the worker runs at most four times:
the first attempt plus three retries.
The CancellationException branch matters. CoroutineWorker cancels the
coroutine when the work is stopped, and a blanket catch (e: Exception) would
turn that cancellation into a logged “failure”. Rethrowing keeps structured
concurrency intact.
3. Backup recovery
private suspend fun restoreFromBackup(backup: File, main: File): Result { Timber.i("[$resourceKey] Main file missing — restoring from backup") return try { backup.copyTo(main, overwrite = true) Timber.i("[$resourceKey] Backup restored successfully") processAndSucceed(main) } catch (e: Exception) { Timber.e(e, "[$resourceKey] Failed to restore backup") Result.failure() }}copyTo(overwrite = true) is safe here because we only reach this branch when
main does not exist. The overwrite flag is a guard against a race where the
file is created by another process between the exists() check and the copy.
4. Running processFile on IO
The abstract processFile is the only method subclasses implement. The base
class wraps it with withContext(Dispatchers.IO) so subclasses do not have to.
protected suspend fun runFileProcessing(file: File): Int = withContext(Dispatchers.IO) { processFile(file) }
private suspend fun processAndSucceed(file: File): Result { val written = runFileProcessing(file) showCompletionNotification(written) return Result.success()}5. Progress notification helpers
Both helpers are protected so subclasses can call showProgressNotification()
from inside their batch loop. The completion notification is private — only
processAndSucceed calls it.
protected fun showProgressNotification(current: Int, total: Int) { val notification = notificationBuilder .setContentTitle("Syncing $resourceKey") .setContentText("$current / $total") .setProgress(total, current, false) .setOngoing(true) .build() safeNotify(notificationId, notification)}
private fun showCompletionNotification(rowsWritten: Int) { val notification = notificationBuilder .setContentTitle("$resourceKey ready") .setContentText("$rowsWritten items loaded") .setProgress(0, 0, false) // clears the progress bar .setOngoing(false) .build() safeNotify(notificationId, notification)}setProgress(0, 0, false) with zero max and zero progress removes the progress
bar from the notification. Without this call, a completed worker leaves a full
progress bar visible in the notification shade until the notification is
dismissed manually.
6. Permission-safe notify
Android 13 requires POST_NOTIFICATIONS at runtime. A user can revoke the
permission between the initial check and the actual notify() call — the SDK
throws a SecurityException in that window.
private fun safeNotify(id: Int, notification: android.app.Notification) { if (!hasNotificationPermission()) return try { notificationManager.notify(id, notification) } catch (e: SecurityException) { // Permission revoked between check and notify — log and continue. // The worker must not fail because of a missing notification. Timber.w(e, "[$resourceKey] Notification permission revoked at runtime") }}
private fun hasNotificationPermission(): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true return ContextCompat.checkSelfPermission( applicationContext, Manifest.permission.POST_NOTIFICATIONS ) == PackageManager.PERMISSION_GRANTED}The pre-API-33 early return is important. POST_NOTIFICATIONS did not exist
before Android 13 — calling checkSelfPermission for it on older APIs returns
PERMISSION_DENIED even when the app has notification capability, which would
silence all progress updates on the majority of devices in the field.
7. A concrete subclass
With the base class in place, each worker is ~40 lines: constructor boilerplate, three overrides, and the batch loop.
@HiltWorkerclass WritePartsToDatabase @AssistedInject constructor( @Assisted context: Context, @Assisted workParameters: WorkerParameters, private val partsDao: PartsDao, @StickyNotification notificationManager: NotificationManagerCompat, @StickyNotification notificationBuilder: NotificationCompat.Builder, progressRepository: ProgressRepository) : BaseWriteToDatabase( context, workParameters, notificationManager, notificationBuilder, progressRepository, notificationId = NotificationIds.PARTS) { override val fileName = "parts.json" override val resourceKey = "parts"
override suspend fun processFile(jsonFile: File): Int { val parts: PartsResponse = jsonFile.convertJsonToDataClass() val total = parts.size var totalInserted = 0
progressRepository.notifyProcessingStart(resourceKey) progressRepository.notifyProgressUpdate(0, total, resourceKey) showProgressNotification(0, total)
for ((index, batch) in parts.toEntity().chunked(BATCH_SIZE).withIndex()) { if (isStopped) { Timber.w("[$resourceKey] Worker stopped at batch $index") break } try { partsDao.insertAll(batch) totalInserted += batch.size } catch (e: Exception) { Timber.w(e, "[$resourceKey] Batch $index failed — ${batch.size} rows skipped") } progressRepository.notifyProgressUpdate(totalInserted, total, resourceKey) showProgressNotification(totalInserted, total) }
progressRepository.notifyProgressUpdate(total, total, resourceKey) progressRepository.notifyProcessingComplete(resourceKey) return totalInserted }}The isStopped check inside the batch loop is the critical detail.
WorkManager can request cancellation at any time — without this guard, the loop
runs to completion even after the work has been cancelled, holding the IO thread
and leaving partially-inserted data in the database.
Note the plain for loop. An earlier version used forEachIndexed with
return@forEachIndexed, which looks like an early exit but only skips the
current batch: the lambda returns and the loop moves on to the next one. If you
need to stop iterating, use a real loop and break.
Testing
./gradlew connectedAndroidTest --tests "*.WritePartsToDatabaseTest"
BUILD SUCCESSFUL in 18s4 instrumented tests completedTest the retry logic by not placing the JSON file before the test runs and
asserting that the work info state reaches ENQUEUED (retrying) before
eventually reaching FAILED after the final retry. Use WorkManagerTestInitHelper and TestDriver.setAllConstraintsMet / setInitialDelayMet so the test does not wait out real backoff delays.
Pitfalls
Production considerations
The base class uses getExternalFilesDir() to locate JSON files. This is
app-specific storage: it persists across process restarts, needs no storage
permission on API 19+, and is not readable by other apps under scoped storage.
It is also cleared when the user uninstalls or clears app data. If the data is large and
should survive uninstall (unlikely for seeding data), use getFilesDir()
instead and manage the migration yourself.
A failed batch is currently logged and skipped. For inventory data where
every row matters, consider collecting failed batches and retrying them after
the main loop completes, or returning Result.failure() if the failed row
count exceeds a threshold percentage of the total.
Wrapping up
You now have a base class that handles file routing, backup recovery, bounded
retries, batched inserts, and permission-safe progress notifications in one
place. Each concrete worker supplies a filename, a resource key, and a
processFile implementation — nothing more.
The phased dependency graph that orchestrates all seven workers runs in
WorkManagerUtil.writeAllToDatabaseWithDependencies(), covered in
Part 3.
Going deeper
Make each batch atomic. insertAll(batch) on a Room @Insert method
already runs in its own transaction. If a batch must be written together with
other tables (for example parts and their category join rows), wrap both
in database.withTransaction { } so a cancellation between them can’t leave
orphans.
Don’t share one notification builder. NotificationCompat.Builder is
mutable. If Hilt provides a single @StickyNotification builder as a
singleton, two workers running in parallel will overwrite each other’s title
and progress between set…() and build(). Provide the builder with an
unscoped binding so each worker gets a fresh instance, or build notifications
from immutable parameters inside the worker.
Long work wants a foreground worker. Since WorkManager 2.3 a worker can
call setForeground(getForegroundInfo()) to run as a foreground service with
an ongoing notification. For a multi-minute seed of a 50,000-row table this
protects the job from being stopped under memory pressure. On Android 14+ you
must also declare a foreground service type (dataSync) in the manifest.
Stream large files instead of loading them whole. convertJsonToDataClass()
reads the entire file into memory before chunking. For the largest datasets,
a streaming parser (Moshi’s JsonReader or kotlinx.serialization’s
decodeToSequence) lets you read and insert one chunk at a time, keeping
peak memory flat regardless of file size.