WorkManager set up with KOIN

Viewed 2491

I'm trying to set up work manager to do some work and I'm having trouble initializing it. Im using KOIN workmaanger dsl

implementation "org.koin:koin-androidx-workmanager:2.2.0-rc-4"

and my worker class looks like this

class NotificationsScheduler(
    private val dispatchers: AppCoroutineDispatchers,
    private val getTaskUseCase: GetTaskUseCase,
    private val context: Context,
    private val workerParameters: WorkerParameters
) : Worker(context, workerParameters) {

    override fun doWork(): Result {
    ...
    }

What I've done so far is disabled default initializer

<provider
    android:name="androidx.work.impl.WorkManagerInitializer"
    android:authorities="${applicationId}.workmanager-init"
    tools:node="remove" />

My worker module is set up like this

val workerModule = module {
    worker { NotificationsScheduler(get(), get(), get(), get()) }
}

and it is added in list used in startKoin DSL. I've also used workManagerFactory() DSL to set up factory.

startKoin {
        androidContext(this@MyApplication)
        workManagerFactory()
        modules(koinModules)
    }

What I'm having trouble with, is that it crashes when app start with exception:

 Caused by: org.koin.core.error.NoBeanDefFoundException: No definition found for class:'androidx.work.WorkerParameters'. Check your definitions!
1 Answers

Just take NotificationsScheduler class implements KoinComponent and inject the AppCoroutineDispatchers and GetTaskUseCase instances by inject() like this:

class NotificationsScheduler(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters), KoinComponent {
    private val dispatchers: AppCoroutineDispatchers by inject()
    private val getTaskUseCase: GetTaskUseCase by inject()
}

In worker module:

val workerModule = module {
    worker { OneTimeWorkRequestBuilder<AlarmNotificationHandleWorker>().run{
         WorkManager.getInstance(androidContext())
         .enqueueUniqueWork(UUID.randomUUID().toString()
         ,ExistingWorkPolicy.APPEND, this)
        } 
    }
}

Make sure you had provided the GetTaskUseCase and AppCoroutineDispatchers instances Updated: Koin 2.2.0 release:

implementation "org.koin:koin-androidx-workmanager:2.2.0"

Update your Worker class

 class NotificationsScheduler(private val dispatchers: AppCoroutineDispatchers,private val getTaskUseCase: GetTaskUseCase,context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters), KoinComponent {
       
  }

And here you are:

val workerModule = module {
        worker { NotificationsScheduler(get(),get(),androidContext(),get())  }
    }

Thanks @p72b

Related