使用 KOIN 设置 WorkManager

WorkManager set up with KOIN

我正在尝试设置工作管理器来完成一些工作,但在初始化时遇到了问题。 我正在使用 KOIN workmaanger dsl

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

我的工人class看起来像这样

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 {
    ...
    }

到目前为止我所做的是禁用默认初始化程序

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

我的worker模块是这样设置的

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

并且它被添加到 startKoin DSL 中使用的列表中。我还使用 workManagerFactory() DSL 来设置工厂。

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

我遇到的问题是,当应用程序启动时出现异常时它会崩溃:

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

只需 NotificationsScheduler class 实现 KoinComponent 并通过 inject() 注入 AppCoroutineDispatchers 和 GetTaskUseCase 实例,如下所示:

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

在工作模块中:

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

确保您提供了 GetTaskUseCase 和 AppCoroutineDispatchers 实例 已更新Koin 2.2.0 release

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

更新您的 Worker class

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

你在这里:

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

谢谢@p72b