Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 802
dudi Avatar asked Oct 19 '25 15:10

dudi


2 Answers

@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() { 
like image 191
Homan Huang Avatar answered Oct 22 '25 03:10

Homan Huang


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.

like image 39
Nitrodon Avatar answered Oct 22 '25 03:10

Nitrodon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!