Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the worker parameters to WorkManager class

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>

like image 700
Shailendra Madda Avatar asked Oct 27 '22 23:10

Shailendra Madda


1 Answers

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.

like image 76
Sergey Avatar answered Oct 31 '22 08:10

Sergey