DEV Community

Discussion on: WorkManager for Background location updates

Collapse
 
hiral1987 profile image
Hiral Dharod • Edited

How to create & pass someRepository instance to UpdateLocationWorker class?

Collapse
 
bigyan4424 profile image
Bigyan Thapa

@Hiral For that, you will need to implement your own WorkerFactory class and set the worker configuration in your Application class. Something like below:

class DevApplication : Application, Configuration.Provider {
...

@Override 
fun getWorkManagerConfiguration() : Configuration {
  return Configuration.Builder()
              .setWorkerFactory( DevWorkerFactory(this)
              .build()
 }
class DevWorkerFactory(private val application: DevApplication) : WorkerFactory() {
  ...
    override fun createWorker(appContext: Context, workerClassName: String, workerParameters: WorkerParameters) : ListenableWorker? {
     return  when(workerClassName) {
                     DevWorker::class.java.canonicalName -> DevWorker(
                     appContext, workerParameters, DevRepository()
                     )
                    else -> null
     }
} 
class DevWorker( appContext: Context, workerParameters: WorkerParameters, private val devRepository: DevRepository) : CoroutineWorker(appContext, workerParameters) {

    override suspend fun doWork() : Result {
          TODO("Do work with repository")
    }
   ...
}

This is one way of implementing this. If you are familiar with DI tools like dagger, there are other ways of implementing this.
I hope this helps.

Collapse
 
hiral1987 profile image
Hiral Dharod

thank u. This should work.