Published in


Injecting into Worker’s — Android WorkManager and Dagger

Background task execution has always been a topic of discussion in the realm of Android development and there are so many ways to achieve that but that’s a thing for some other time — just google it :) 🤡

My recent interaction with WorkManager was awesome and I loved how easy it was to implement and execute but modern Android development is incomplete without dependency injection specifically Dagger 🤷🏻‍♂️and that’s where I ran into a problem.

Let’s jump right into the code:

Example worker class would look like this

Until its an independent task everything is fine but usually not the case. Taking an example where MyWorker requires a repository to access some data from the database and perform some network calls to sync with the server.

Updated MyWorker would look something like this:

And in the module, we provide it into a map similar to ViewModel

All looks good until you realise where will you get Context and WorkerParameters from?? We never provided those into our dagger graph and moreover, these workers are instantiated by WorkManager.

The Solution

This problem was familiar as we faced the same issue with ViewModels and to our rescue came the ViewModelFactory. So using the same fundamentals we MultiBind our workers and create a factory which will take care of instantiating these Workers with dependencies. Hah Easy!! 😎

WorkManager provides an abstract WorkerFactory class which our factory can use to instantiate workers.

Remember, there is always a BUT!

That’s not enough since we are still injecting our Worker directly which in turn requires the Context and WorkerParameter. 😓

To solve this, think of it like what if instead of binding workers directly we bind another factory which is responsible for instantiating that worker only, as a child factory.

We create our own ChildWorkerFactory to be implemented by each workers factory.

Our MyWorker now looks like this

And then in our module, instead of Worker we bind child factory of MyWorker.

and Now our MyWorkerFactory looks like this

Now that everything is set all we need to do is tell our WorkManager to use our factory. In Application class

And that’s about it. Really!! 🕺🏻💃🏻

And in the app, WorkManager and Dagger lived happily ever after

If you are still reading then there’s another party trick. If you don’t like writing factories inside those workers then I’d recommend using either AutoFactory or AssistedInject.

Well, that’s it for this article. Happy Coding, Cheers!!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store