Dagger 2 setup with WorkManager, a complete step by step guide

This is great because through our custom factory we can now decide how to construct Worker instance, not restricted to the default constructor anymore.TL; DR with the introduction of WorkerFactory we can now perform constructor inject in our worker.​The idea is simple..Each worker will have an inner class called Factory, this factory responsible for supply dependencies for the parent Worker..We will annotate this factory with @Inject, all of the worker’s dependencies will go there left out only the WorkerParameters..Then in the create method, we instantiate our worker with all the parameter we need..And since every worker have this common method it is reasonable to make an interface for it (let call it ChildWorkerFactory, this interface, later on, become useful since we will work with Dagger multi-binding)In this step dagger already know how to inject the HelloWorldWorker.Factory since all of its dependence is fulfilled (notice how we left out the WorkerParameters for the create() method)Move on to the dagger multi-binding setup for ChildWorkerFactoryThe setup is straightforward, we bind HelloWorldWorker.Factory (a.k.a ChildWorkerFactory) into dagger multibind map with a WorkerKeyFinally, the SampleWorkerFactory — the custom factory that we will register with WorkerManager.Note: remember to register this factory inside your Application#onCreate() and AndroidManifest.xml, more on that here or look at the source code in the end of this post.We then hit the run button…D/HelloWorldWorker: Hello world!D/HelloWorldWorker: Injected foo: com.sample.daggerworkmanagersample.Foo@215b58d0I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=c1628749-ed19-4b11-b027-95031d3b3bae, tags={ com.sample.daggerworkmanagersample.HelloWorldWorker } ]Yay…!!!Factories for daysThe problem is not stopping there..We now end up with a double factory setup..SampleWorkerFactory lookup for ChildWorkerFactory then uses that factory to construct the corresponding Worker instance.Writing those factories is annoying, it is still acceptable if your worker doesn’t have many dependencies..But imagine your app need 10 Worker, each of those requires 10 dependence, that means 10 extra ChildWorkerFactory implementations needed to write manually..Now that becomes a big problem..How can we solve this?​This is where AssistedInject comes to play..A library by Square that compatible with Dagger 2, it generates all of the ChildWorkerFactory implementations for us and also bind the generated implementation to Dagger..Read more about it here.​Setup our existing code base with AssistedInject is simple.. More details

Leave a Reply