In one of my android(with Kotlin) app I want to use WorkManager class as a generic one.
This is my class where I want to use it as generic by passing expected params:
class CommonWorkManager<P, R> (appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams)
{
var lambdaFunction: ((P) -> R)? = null
override fun doWork(): Result {
lambdaFunction
return Result.SUCCESS
}
}
This is how I am trying to create an instance of this class:
CommonWorkManager<Unit, Unit>(context!!, ).lambdaFunction= {
presenter?.fetchMasterData()
}
So How can I pass workerParams
as a second param.
Here 'P' is Parameter and 'R' is Return type in CommonWorkManager<P, R>
It seems we can't create instances of WorkerParameters
because it has hidden constructor with annotation @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
.
According to the documentation we don't create instances of Worker
subclass, the library does it for us:
First, you would define your Worker
class, and override its doWork()
method. Your worker class specifies how to perform the operation, but doesn't have any information about when the task should run. Next, you create a OneTimeWorkRequest
object based on that Worker
, then enqueue the task with WorkManager
:
val work = OneTimeWorkRequest.Builder(CommonWorkManager::class.java).build()
WorkManager.getInstance().enqueue(work)
We can conclude that we can't create universal Worker
, i.e. CommonWorkManager<P, R>
in your case. WorkManager
is intended for the specific tasks.