我想用Dagger2注入一个WorkManager实例,以便像这样在我的ViewModel中使用它
class MyViewModel @Inject constructor(workManager: WorkManager) : ViewModel()
当我尝试为WorkManager创建模块以提供其实例时,出现一条错误消息,提示我不能从抽象类提供。如何在ViewModel构造函数中注入WorkManager实例?
答案 0 :(得分:2)
要获取没有Dagger的WorkManager
实例,可以使用WorkManager.getInstance(context)
。要将WorkManager
放入Dagger的对象图中,我们只需要将此代码放入@Provides
方法中即可。
@Provides
// Maybe @Singleton, though it really doesn't matter.
fun provideWorkManager(context: Context): WorkManager = WorkManager.getInstance(context)
在Dagger模块中使用此方法,只要您的组件可以访问WorkManager
,就可以在任何地方注入Context
。
答案 1 :(得分:2)
@Module
@InstallIn(SingletonComponent::class)
object YourModule {
@Provides
@Singleton
fun provideWorkManager(@ApplicationContext appContext: Context): WorkManager =
WorkManager.getInstance(appContext)
}
注入到视图模型:
@HiltViewModel
class YourViewModel @Inject constructor(
val workManager: WorkManager
) : ViewModel() {