Search code examples
androidkotlindagger-2android-architecture-componentsandroid-workmanager

issue in while using `WorkContinuation.combine()` when WorkManger is initialized using dagger2


I've been using workManager and it works fine with dagger2 but when i used WorkContinuation.combine() for chaining there was an issue in WorkerFactory My workers didn't initialze

crash report is

java.lang.IllegalArgumentException: unknown worker class name: androidx.work.impl.workers.CombineContinuationsWorker
        at incubasys.aydo.repositories.worker.WorkerFactory.createWorker(WorkerFactory.kt:22)
        at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:81)
        at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:228)
        at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:127)
        at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:75)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)

WorkerFactory where the crash happens

class DaggerWorkerFactory @Inject constructor(
    private val workerFactories: Map<Class<out ListenableWorker>, @JvmSuppressWildcards Provider<ChildWorkerFactory>>
) : WorkerFactory() {
    override fun createWorker(
        appContext: Context,
        workerClassName: String,
        workerParameters: WorkerParameters
    ): ListenableWorker? {
        val foundEntry =
            workerFactories.entries.find { Class.forName(workerClassName).isAssignableFrom(it.key) }
//crashes here
        val factoryProvider = foundEntry?.value
            ?: throw IllegalArgumentException("unknown worker class name: $workerClassName")
        return factoryProvider.get().create(appContext, workerParameters)
    }
}

it only crashes when i use WorkContinuation.combine().


Solution

  • WorkContinuation.combine() adds an instance of the CombineContinuationsWorker class to your continuation.
    This means that your WorkerFactory needs to handle this class names when creating the actual worker class.

    You have two options:

    1. You handle CombineContinuationsWorker to your workerFactory
    2. You use a delegatingWorkerFactory and add your factory to it so that it returns null when it does not find the correct class name. The delegatingWorkerFactory will then use the default workerFactory to instantiate the right class.

    Personally I prefer the second option as it handles whatever will change in WorkManager and you can potentially add more/different Worker Factories that handle different pieces/module of your application.