Search code examples
androidgradleleakcanary

How can I include LeakCanary when using both build types and product flavors?


The LeakCanary documentation mentions the following for handling build types:

 dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
 }

However, what about when using multiple product flavors as well? I'm receiving an error Gradle DSL method not found on the buildTypeCompile functions.

Here is a skeleton of my current Gradle file:

android {
    ...

    dependencies {
        debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
        ciCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
        qaCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
        uatCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
        prodCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
        releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
    }

    productFlavors {
        foo {
            buildTypes {
                ci {
                    ...
                }

                qa {
                    ...
                }
            }
        }

        bar {
            buildTypes {
                ci {
                    ...
                }

                qa {
                    ...
                }
            }
        }
    }
}

Solution

  • build.gradle is a script that builds up an object model of the build process. However, it is still a script, written in a scripting language (Groovy), and as such tends to be processed top-down.

    Methods, like debugCompile, are generated when their corresponding object model objects are created. In the case of debugCompile and releaseCompile, since the debug and release build types are pre-defined, order does not matter too much. But for custom build types, and any product flavors, you need to define those first, before you try using generated methods.

    The safest spot for module-level build.gradle file dependencies closures is at the end, after you're sure all your build types and product flavors exist, and therefore the corresponding ...Compile methods exist.

    Personally, I like having dependencies before android, and if you don't have custom build types or product flavors, that'll work.