Android Hilt Worker — Complete Guide
In this tutorial, you'll learn about Android Hilt Worker. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your Worker injected with Hilt throws a NoSuchMethodException or Hilt can't create the worker because it expects a default constructor.
Wrong Approach ❌
// No @HiltWorker — Hilt ignores this worker
class SyncWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var api: ApiService // Always null!
}
// Missing @HiltAndroidApp in Application
class App : Application() { /* No annotation */ }
Output: ApiService is null. DefaultWorkerFactory can't create the worker.
Right Approach ✅
@HiltAndroidApp
class App : Application() {
override fun onCreate() {
super.onCreate()
// Hilt initializes WorkManager configuration
}
}
@HiltWorker
class DataSyncWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted workerParams: WorkerParameters,
private val apiService: ApiService,
private val repository: UserRepository
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
return try {
val data = apiService.fetchData()
repository.saveData(data)
Result.success()
} catch (e: Exception) {
if (runAttemptCount < 3) Result.retry() else Result.failure()
}
}
}
Output: Worker with full Dependency Injection. Hilt creates it via HiltWorkFactory.
Prevention
- Annotate Application with
@HiltAndroidApp. - Annotate Worker with
@HiltWorkerand@AssistedInject. - Use
HiltWorkFactory(automatically configured by Hilt). - Add
hilt-Android-workdependency to yourbuild.gradle.
Common Mistakes with hilt worker
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro