Search code examples
androidviewmodeldagger-2daggerandroid-workmanager

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?


Solution

  • 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.