如何将辅助参数传递给WorkManager类 [英] How to pass the worker parameters to WorkManager class
问题描述
在我的一个带有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()
}
那么我如何将workerParams
作为第二个参数传递.
So How can I pass workerParams
as a second param.
在CommonWorkManager<P, R>
推荐答案
似乎我们无法创建WorkerParameters
的实例,因为它具有带注释@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
的隐藏构造函数.
根据文档,我们不会创建Worker
子类,图书馆为我们做到了:
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:
首先,您将定义您的
Worker
类,并覆盖其doWork()
方法.您的工作程序类指定了执行操作的方式,但是没有有关任务何时运行的任何信息.接下来,基于Worker
创建一个OneTimeWorkRequest
对象,然后使用WorkManager
将任务加入队列:
First, you would define your
Worker
class, and override itsdoWork()
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 aOneTimeWorkRequest
object based on thatWorker
, then enqueue the task withWorkManager
:
val work = OneTimeWorkRequest.Builder(CommonWorkManager::class.java).build()
WorkManager.getInstance().enqueue(work)
我们可以得出结论,我们无法创建通用的Worker
,即您的情况下的CommonWorkManager<P, R>
. WorkManager
用于特定任务.
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.
这篇关于如何将辅助参数传递给WorkManager类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!