今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

标签:#hilt

找到 1 篇相关文章

AI 资讯

Injecting WorkManager into ViewModels with Dagger Hilt. No Context, No Boilerplate, Always a WorkQuery Back

WorkManager is the right tool for deferrable, guaranteed background work in Android. But the default setup pushes you toward boilerplate fast: you end up calling WorkManager.getInstance(context) inside ViewModels, "passing Context where it doesn't belong", re-registering observers scattered across the codebase, and getting no consistent way to query the state of your enqueued work. This tutorial shows how to build a clean, injectable WorkManagerHandler using Dagger Hilt, a single interface that any ViewModel can receive through constructor injection, with zero Context and a guaranteed WorkQuery callback on every call so you always know what to observe. By the end, you'll have: A WorkManager singleton provided through Hilt A custom Configuration.Provider that plugs Hilt's HiltWorkerFactory into WorkManager at initialization A WorkManagerHandler interface with a WorkManagerHandlerImpl that encapsulates enqueueing, chaining, and query registration ViewModels that declare WorkManagerHandler as a plain constructor dependency The pattern scales cleanly as you add workers: each new worker is one method on the handler, and the ViewModel never knows or cares how work is scheduled underneath. Prerequisites : familiarity with Dagger Hilt basics, Jetpack WorkManager fundamentals, and Kotlin coroutines. A working Android project with Hilt already configured is assumed. Part 1: Application Setup and Custom Configuration.Provider By default, WorkManager initializes itself automatically using its own internal factory. The problem is that Hilt-injected workers need Hilt's factory HiltWorkerFactory to resolve their @Inject constructor dependencies. If you let WorkManager self-initialize, your workers won't have access to any of your Hilt bindings. The fix is to disable auto-initialization and take manual control via Configuration.Provider and AndroidManifest.xml 1. Disable auto-initialization In your AndroidManifest.xml , remove WorkManager's default initializer: <application ... > <

2026-06-10 原文 →