A Cleaner Android Application Design with Dagger 2 (Kotlin example)
In Android, Application classes tend to get huge and out of hand pretty fast, because of all configuration that is meant for them to do.
Here is an example of such (the details are not important):
It’s a wreck. Every new configuration is simply added to the onCreate() method or divided into multiple methods, but is still in the Application class.
Luckily with Dagger, we can create a simple solution for this with multibindings.
Dagger Multibindings
With Dagger, we can provide a Set or a Map of dependencies of the same type by simply annotating the provide methods in a module with @IntoSet annotation. Because of that, we will create an ApplicationConfig interface.
interface ApplicationConfig {
fun configure()
}We are then going to encapsulate all of the configuration from the application class in separate classes. For Timber, we create TimberConfig, for Crashlytics create CrashlyticsConfig and so on…
So, for example, TimberConfig looks like this:
Next, create ConfigModule which provides all config objects. Notice that all provide methods are annotated with the @IntoSet annotation and return the same type (ApplicationConfig).
Result
Now in our Application class, we can simply inject that Set of config objects, iterate on it and call the configure() method and that’s it! The Application class is stripped to a minimum.
P.S. The @JvmSuppressWildcards annotation is needed because I am using Kotlin. You can read about it more here.
I used this design in my hobby project MyShoppingList so you can see the whole implementation there, or check out my github account:
