DelegatingWorker
A proxy Worker that delegates work to another CoroutineWorker created via HiltWorkerFactory.
Why This Pattern Exists
Problem
WorkManager creates Worker instances using reflection, which prevents Hilt from automatically injecting dependencies. The standard solution requires configuring a custom WorkManager initializer in the app module, which creates tight coupling and violates separation of concerns.
Solution
This delegating pattern allows library modules (like :sync) to define Workers with injected dependencies WITHOUT requiring the app module to configure WorkManager. Instead:
The app module enqueues a generic
DelegatingWorkerDelegatingWorkerreceives the actual Worker class name via input dataDelegatingWorkeruses Hilt's entry point to getHiltWorkerFactoryHiltWorkerFactorycreates the real Worker with all dependencies injectedDelegatingWorkerdelegates all work to the real Worker
Benefits
Modular: Library modules can define Workers without app module configuration
Type-safe: Compile-time verification of Worker classes via
delegatedData()extensionClean: App module doesn't need custom WorkManager initialization
Testable: Real Workers can be tested independently with mock dependencies
Usage Pattern
// 1. Define a Worker in a library module with dependencies
@HiltWorker
class SyncWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted params: WorkerParameters,
private val repository: Repository // Injected by Hilt!
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result { /* ... */}
}
// 2. Enqueue DelegatingWorker with metadata pointing to the real Worker
val workRequest = OneTimeWorkRequestBuilder<DelegatingWorker>()
.setInputData(SyncWorker::class.delegatedData())
.build()
WorkManager.getInstance(context).enqueue(workRequest)Architecture Decision
This pattern was chosen over custom WorkManager configuration because:
It keeps WorkManager initialization in the app module simple
Library modules remain self-contained and reusable
No need for app module to know about library module Workers
Follows separation of concerns principle
Parameters
The application context provided by WorkManager
The worker parameters containing input data with the delegate Worker class name
See also
Properties
Functions
Delegates the actual work execution to the real Worker.
Delegates foreground info retrieval to the actual Worker.