How to pass the worker parameters to WorkManager class
Asked Answered
T

1

6

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>

Tantalate answered 19/12, 2018 at 11:39 Comment(1)
i think that question have your answer: #52422861Phosphocreatine
L
2

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.

Lycia answered 19/12, 2018 at 12:53 Comment(3)
Thanks for the reply, This is to just start work, but I want to create an instance by passing expected parameters to it and assign value to the lambdaFunction variableTantalate
Have you read this?Gestation
@Gestation it's just about sending object! what about interface (Unit in Kotlin)? I'm looking for a way to use one Worker class and use it for all part of my project. Do you have any idea to do that?Sphacelus

© 2022 - 2024 — McMap. All rights reserved.