How to pass the worker parameters to WorkManager class

时间:2018-12-19 11:39:51

标签: kotlin android-workmanager

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>

1 个答案:

答案 0 :(得分:0)

似乎我们无法创建WorkerParameters的实例,因为它具有带注释@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)的隐藏构造函数。 根据{{​​3}},我们没有创建Worker子类的实例,该库为我们做到了:

  

首先,您将定义Worker类,并覆盖其doWork()方法。您的工作程序类指定了执行操作的方式,但是没有有关任务何时运行的任何信息。接下来,您基于该OneTimeWorkRequest创建一个Worker对象,然后使用WorkManager使该任务排队:

val work = OneTimeWorkRequest.Builder(CommonWorkManager::class.java).build()
WorkManager.getInstance().enqueue(work)

我们可以得出结论,我们无法创建通用的Worker,即您所创建的CommonWorkManager<P, R>WorkManager用于特定任务。