dudi
dudi

Reputation: 5732

How to inject WorkManager instance in a ViewModel constructor with Dagger2?

I want inject a WorkManager instance with Dagger2 to use it in my ViewModel like this

class MyViewModel @Inject constructor(workManager: WorkManager) : ViewModel()

When I try to create a Module for WorkManager to provide an instance of it I getting an error that says, I can't provide from an abstract class. How can inject an instance of WorkManager in my ViewModel constructor?

Upvotes: 4

Views: 2589

Answers (2)

Homan Huang
Homan Huang

Reputation: 433

@Module
@InstallIn(SingletonComponent::class)
object YourModule {    
    @Provides
    @Singleton
    fun provideWorkManager(@ApplicationContext appContext: Context): WorkManager =
        WorkManager.getInstance(appContext)
}

Inject to ViewModel:

@HiltViewModel
class YourViewModel @Inject constructor(
    val workManager: WorkManager
) : ViewModel() { 

Upvotes: 5

Nitrodon
Nitrodon

Reputation: 3435

To get an instance of WorkManager without Dagger, you would use WorkManager.getInstance(context). To put WorkManager in the object graph in Dagger, we simply need to put this code in a @Provides method.

@Provides
// Maybe @Singleton, though it really doesn't matter.
fun provideWorkManager(context: Context): WorkManager = WorkManager.getInstance(context)

With this method in a Dagger module, you will be able to inject WorkManager anywhere, provided your component has access to a Context.

Upvotes: 4

Related Questions