Modularization is a good instrument for constructing an app at scale, nonetheless care should be taken to make sure that assets shared between modules are correctly instantiated. WorkManager
offers a default configuration that’s utilized on app begin up. That is typically handy, however in a modularized app the place totally different modules typically have totally different dependencies, WorkManager’s
default configuration will not be sufficient. This weblog submit particulars how we arrange WorkManager
to be used within the multi module Now in Android app.
WorkManager
exists as a singleton occasion. To offer customized configuration for this occasion in a single module app, you may implement a Configuration.Supplier
that gives parameters for the Executor
used to carry out work. You can too implement a WorkerFactory
to help in dependency injection when utilizing WorkManager
with Hilt.
Issues get extra nuanced in a multi-module app. Which module must be answerable for configuring the WorkManager
occasion? If such a module exists, wouldn’t it have to rely upon all modules that want employees? Wouldn’t that break the “low cohesion” precept when modularizing apps? It will, so as a substitute, we lean on one other software program engineering precept: delegation.
Making a DelegatingWorker
WorkManager
WorkerFactory
cases can create Employee
cases at runtime given:
Whenever you couple this with Hilt entry factors, it turns into potential to dynamically delegate to Employee
cases lazily with out having to implement the Configuration.Supplier
in a central location. The skeleton for such an implementation follows:
The above code determines what Employee
the app ought to delegate to. To take action, it reads the totally certified identify of the Employee
class from the WorkerParameters
. As soon as it has that, it takes the HiltWorkerFactoryEntryPoint
from the appliance Context
and makes use of it to instantiate the given Employee
.
See the next snippet for an instance of a utility technique you can use to go the totally certified identify of the employee to the DelegatingWorker
by way of the WorkerParameters
:
To make use of the above perform, create a WorkRequest
concentrating on the DelegatingWorker
, after which add some other metadata wanted for the work within the delegated Employee
. Within the snippet to comply with, the delegated Employee
is the SyncWorker
.
Lastly, enqueue the work as standard:
Use of a DelegatingWorker
occasion is helpful in additional than simply multi-module apps. It’s also helpful for libraries who want to make use of WorkManager
however can not go their dependencies simply to the apps that rely upon them.
A helpful rule of thumb is, for those who shouldn’t have handy entry to the Software
occasion in app and you’ll want to name on WorkManager
, use a delegating employee to lazily create your precise Employee
with the required WorkerFactory
.