如何将辅助参数传递给WorkManager类 [英] How to pass the worker parameters to WorkManager class

查看:612
本文介绍了如何将辅助参数传递给WorkManager类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个带有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 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)

我们可以得出结论,我们无法创建通用的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆