Step #5: Injecting Into the Worker

To do the import, we need:

Elsewhere in the app, we get those from Koin. However, elsewhere in the app, we tend to be working with either Koin-defined objects (e.g., repositories) or common Android/Jetpack classes (Fragment, ViewModel, etc.). A CoroutineWorker is none of those.

However, Koin still supports classes like CoroutineWorker (and our ImportWorker subclass). To do this, just add KoinComponent as an interface to ImportWorker:

class ImportWorker(context: Context, params: WorkerParameters) :
  CoroutineWorker(context, params), KoinComponent {

This lets us use by inject() property delegates to retrieve objects from Koin. So, add these two properties to ImportWorker to pull in our repositories:

  private val repo: ToDoRepository by inject()
  private val prefs: PrefsRepository by inject()

At runtime, by inject() will reach into the Koin object manager and retrieve our desired objects.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.