Search code examples
androidkotlindagger-2android-productflavors

Provide Dagger flavor-specific module


I have an application with 5 flavours. I just want one of them to provide a different dagger module implementation (which the same interface). I don't want to create this module in each flavor, I just want to have a flavor-specific module and a default one for all other flavors. So I've tried to use the directory main to keep the default module, while implementing a different one in one of the flavors. Of course, this does not work as a redeclaration error is thrown.

Is there a way to achieve an aproach like this, to create a default dagger module for all flavors, but an alternative implementation just for one of them?


Solution

  • There are 2 options to achieve this:

    1. Add source set specific modules (src/flavorA/java, src/flavorB/java) for all product flavors and don’t define the module in main source set (as that will throw an error due to redeclaration)

    2. You can add the dagger module in the main source set and have an if else check on the constant for product flavour in the BuildConfig class to provide the relevant implementation for your interface.

    PS: Product flavors in Gradle work by merging the source code for the main and the flavor specific source set hence any class in flavor specific source sets needs to be defined specifically for all flavor source sets and never in main to avoid a compilation error.

    Resources are also merged similarly but in case of a clash between main and flavor source set the latter overrides without any errors