Android
Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
WorkManager's built-in setProgress() emits untyped Data blobs. A listener-based ProgressRepository converts worker callbacks into a typed domain model that flows directly into Compose StateFlow without polling.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 8 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
WorkManager’s built-in setProgress() emits Data blobs — untyped key-value
pairs. The UI reads them from WorkInfo.progress, extracting integers
by string key, and manually computing percentages. With seven database
workers each emitting progress, the UI ends up observing seven LiveData
streams and combining untyped integers into display strings.
A ProgressRepository with a DatabaseProgressListener interface inverts
this: workers push typed events, a ViewModel collects them into a StateFlow<DatabaseProgress>,
and Compose observes the flow. One stream, typed domain model, no polling.
Prerequisites
WorkManager 2.11.1, Hilt 2.56, Compose BOM 2025.05, coroutines 1.8.1.
Familiarity with the BaseWriteToDatabase worker from Part 4.
Background
BaseWriteToDatabase calls progressRepository.notifyProgressUpdate(current, total, resourceKey)
on every batch insert. The repository holds a list of registered listeners
and forwards the call to each one. A ViewModel registers as a listener in
init, converts the callbacks into MutableStateFlow emissions, and exposes
an immutable StateFlow<DatabaseProgress> to the UI.
DatabaseProgress is a data class with computed properties — progressPercentage,
percentageText, isComplete, itemsText — so the Composable is pure
display logic with no arithmetic.
Implementation
1. ProgressRepository
@Singletonclass ProgressRepository @Inject constructor() {
// Registered on the main thread, iterated from worker threads. private val progressListeners = CopyOnWriteArrayList<DatabaseProgressListener>()
fun registerListener(listener: DatabaseProgressListener) { progressListeners.add(listener) }
fun unregisterListener(listener: DatabaseProgressListener) { progressListeners.remove(listener) }
suspend fun notifyProgressUpdate(current: Int, total: Int, type: String) { progressListeners.forEach { it.onProgressUpdate(current, total, type) } }
suspend fun notifyProcessingStart(type: String) { progressListeners.forEach { it.onProcessingStart(type) } }
suspend fun notifyProcessingComplete(type: String) { progressListeners.forEach { it.onProcessingComplete(type) } }}
interface DatabaseProgressListener { suspend fun onProgressUpdate(current: Int, total: Int, type: String) suspend fun onProcessingStart(type: String) suspend fun onProcessingComplete(type: String)}ProgressRepository is @Singleton — the same instance is injected into
every BaseWriteToDatabase worker and into the ViewModel that observes progress.
The listener list is a CopyOnWriteArrayList because two threads touch it:
registration happens on the main thread (ViewModel init and onCleared),
while notifications iterate it from worker threads. With a plain
mutableListOf(), a ViewModel being created or cleared mid-sync can throw
ConcurrentModificationException inside a worker. Copy-on-write is the right
trade-off here: writes are rare, reads happen on every batch.
2. DatabaseProgress domain model
data class DatabaseProgress( val currentProgress: Int, val totalItems: Int, val itemType: String) { val progressPercentage: Float get() = if (totalItems > 0) currentProgress.toFloat() / totalItems.toFloat() else 0f
val percentageText: String get() = "${(progressPercentage * 100).toInt()}%"
val isComplete: Boolean get() = totalItems in 1..currentProgress
val itemsText: String get() = "$currentProgress / $totalItems"}All display logic is in DatabaseProgress. The Composable receives a
DatabaseProgress and calls .percentageText or .itemsText directly —
no formatting in the ViewModel, no formatting in the Composable.
isComplete checks totalItems in 1..currentProgress rather than
currentProgress >= totalItems to guard against the initial state where
both are 0, which would otherwise evaluate as complete.
3. Worker calls — inside BaseWriteToDatabase
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)
for ((index, batch) in parts.toEntity().chunked(BATCH_SIZE).withIndex()) { if (isStopped) break try { partsDao.insertAll(batch) totalInserted += batch.size } catch (e: Exception) { Timber.w(e, "Batch $index failed") } progressRepository.notifyProgressUpdate(totalInserted, total, resourceKey) showProgressNotification(totalInserted, total) }
progressRepository.notifyProgressUpdate(total, total, resourceKey) progressRepository.notifyProcessingComplete(resourceKey) return totalInserted}Three events per worker run: notifyProcessingStart at the beginning,
notifyProgressUpdate after each batch, notifyProcessingComplete at the end.
The ViewModel handles all three.
4. ViewModel — register, collect, expose
@HiltViewModelclass SettingsViewModel @Inject constructor( private val progressRepository: ProgressRepository, private val workManagerUtil: WorkManagerUtil,) : ViewModel(), DatabaseProgressListener {
private val _dbProgress = MutableStateFlow<DatabaseProgress?>(null) val dbProgress: StateFlow<DatabaseProgress?> = _dbProgress.asStateFlow()
init { progressRepository.registerListener(this) }
override fun onCleared() { progressRepository.unregisterListener(this) super.onCleared() }
override suspend fun onProgressUpdate(current: Int, total: Int, type: String) { _dbProgress.value = DatabaseProgress( currentProgress = current, totalItems = total, itemType = type ) }
override suspend fun onProcessingStart(type: String) { _dbProgress.value = DatabaseProgress(0, 0, type) }
override suspend fun onProcessingComplete(type: String) { // Keep the complete state visible _dbProgress.update { it?.copy(currentProgress = it.totalItems) } }}The ViewModel implements DatabaseProgressListener directly — no anonymous
class, no lambda wrapper. registerListener(this) in init and
unregisterListener(this) in onCleared() means the registration lifetime
matches the ViewModel lifetime exactly.
5. Composable — observe and display
@Composablefun SyncProgressSection(viewModel: SettingsViewModel = hiltViewModel()) { val progress by viewModel.dbProgress.collectAsStateWithLifecycle()
progress?.let { p -> Column { Text( text = "Syncing ${p.itemType}: ${p.itemsText}", style = MaterialTheme.typography.bodyMedium ) LinearProgressIndicator( progress = { p.progressPercentage }, modifier = Modifier.fillMaxWidth() ) if (p.isComplete) { Text( text = "${p.itemType} ready", color = MaterialTheme.colorScheme.primary ) } } }}collectAsStateWithLifecycle() from androidx.lifecycle:lifecycle-runtime-compose stops collecting when
the Composable is not visible, which prevents unnecessary recompositions while
the screen is in the background. Use it instead of collectAsState() for any
StateFlow in a screen-level Composable.
Testing
./gradlew test --tests "*.ProgressRepositoryTest"
BUILD SUCCESSFUL in 2s5 unit tests completedUnit-test ProgressRepository by registering a test listener and asserting
that notifyProgressUpdate calls the listener with the correct arguments.
No WorkManager involvement needed — the repository is a plain Kotlin class.
Pitfalls
Production considerations
With seven workers (at most three running at once) each calling
notifyProgressUpdate every 1,000 rows, and files averaging ~50,000 rows
each, you get roughly 50 callbacks per worker — 350 total across all workers. Each callback triggers a
StateFlow emission and a Compose recomposition. At ~350 total over a
~30-second sync window, that is well within Compose’s recomposition budget.
If files grow significantly larger, add a throttle to notifyProgressUpdate
that skips emissions where the percentage change since the last emission is
less than 1%. This reduces UI churn without losing meaningful progress fidelity.
Wrapping up
You now have a typed, listener-driven progress pipeline: workers push
DatabaseProgress events, a ViewModel bridges them into StateFlow, and
Compose observes the flow with lifecycle awareness. No polling, no untyped
Data extraction, no arithmetic in the UI layer.
This is the final piece of the WorkManager in Production series. The complete pipeline: Hilt setup → worker tags → phased dependency graph → base worker template → DownloadManager orchestration → file backup → structured failure output → typed progress to UI.
Going deeper
One progress value is not enough for parallel workers. Phase 2 runs
parts, gear and minifigures at the same time, and they all write to a single
_dbProgress. The UI flickers between whichever reported last. Keying state
by type fixes it, and an overall figure falls out for free:
@Singletonclass ProgressRepository @Inject constructor() { private val _progress = MutableStateFlow<Map<String, DatabaseProgress>>(emptyMap()) val progress: StateFlow<Map<String, DatabaseProgress>> = _progress.asStateFlow()
fun update(type: String, current: Int, total: Int) = _progress.update { it + (type to DatabaseProgress(current, total, type)) }}
// ViewModel: overall progress across every workerval overall = progressRepository.progress .map { all -> all.values.sumOf { it.currentProgress } to all.values.sumOf { it.totalItems } }MutableStateFlow.update is atomic, so concurrent workers can’t lose each
other’s writes, and there is no listener list to manage or leak.
In-memory progress does not survive process death; setProgress() does.
WorkManager persists WorkInfo.progress, so a UI that comes back after the
process was killed still sees the last value. An in-memory repository starts
empty. For a seeding job that can outlive the UI, consider doing both: push
typed events for a smooth live UI, and call setProgress() on a coarser
interval so a cold start can show where things stand.
Throttle at the source. If batch sizes shrink or files grow, emit only
when the integer percentage changes. distinctUntilChanged() on a mapped
percentage in the ViewModel works too, but throttling in the worker also saves
the notification updates, which are more expensive than recompositions.