Issue with Hilt integration in WorkManagerApplication

68 Views Asked by At

Error: error: [androidx.hilt.work.WorkerAssistedFactory.create(android.content.Context, androidx.work.WorkerParameters)] The parameters in the factory method must match the @Assisted parameters in com.app.workmanagersample.ui.WorkManagerCall.

Code:

@HiltAndroidApp
class WorkManagerApplication() : Application(), Configuration.Provider {
    @Inject
    lateinit var workerFactory: WorkManagerCallFactory
    override val workManagerConfiguration: Configuration
        get() = Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .setMinimumLoggingLevel(android.util.Log.INFO)
            .build()

}


    class WorkManagerCallFactory @Inject constructor(private val api: Api) : WorkerFactory() {
        override fun createWorker(
            appContext: Context,
            workerClassName: String,
            workerParameters: WorkerParameters
        ): ListenableWorker = WorkManagerCall(api, appContext, workerParameters)
    
    }
    
    @HiltWorker
    class WorkManagerCall @AssistedInject constructor(
         @Assisted private val api: Api,
        @Assisted context: Context,
        @Assisted params: WorkerParameters
    ) : CoroutineWorker(context, params) {
        override suspend fun doWork(): Result {
            val userData = UserData("9901907999", 23, "", 39, 23, "")
            return try {
                api.registerUser(userData)
                Log.d("WorkTest", "Success")
                return Result.success()
            } catch (e: HttpException) {
                Log.d("WorkTest", "Failed")
                Result.retry()
            } catch (e: Exception) {
                Log.d("WorkTest", "Failed")
                Result.failure()
            }
        }
    }
1

There are 1 best solutions below

2
Jigar Rangani On

update you WorkManagerCall and remove assited from api paramater and try to rebuild and project and check again

@HiltWorker
class WorkManagerCall @AssistedInject constructor(
    private val api: Api, // Regular injection, not assisted
    @Assisted context: Context, 
    @Assisted params: WorkerParameters 
) : CoroutineWorker(context, params) {
 
}

and remove this

class WorkManagerCallFactory @Inject constructor(private val api: Api) : WorkerFactory() {
        override fun createWorker(
            appContext: Context,
            workerClassName: String,
            workerParameters: WorkerParameters
        ): ListenableWorker = WorkManagerCall(api, appContext, workerParameters)
    
    }

and in application class initialize workmanager with hilt like this

@Inject
    lateinit var workerFactory: HiltWorkerFactory

and make sure you have api service is bind through hilt in you network module or app module