Michał Klimczak
Michał Klimczak

Reputation: 13154

Creating Java library - add Gradle dependency for testing, but don't include it in compiled library (or make it overridable)

I have an Android project and I plan to make one of its components a library. This will be a Java library (jar), as the android dependencies are not needed there.

The problem is that this library depends on RxJava. But I would like it to be dependent on the RxJava version which the library client will use, no to be explicitly provided by me in the library's build.gradle.

I thought that maybe Gradle Default dependencies would be the way to go, but it doesn't provide the RxJava dependency at all and the library module doesn't build.

My build.gradle:

apply plugin: 'java'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

configurations.all {
    pluginTool {
        defaultDependencies { dependencies ->
            dependencies.add(this.project.dependencies.create("io.reactivex:rxjava:1.1.0"))
        }
    }
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

Upvotes: 0

Views: 252

Answers (1)

nandsito
nandsito

Reputation: 3852

The problem is that this library depends on RxJava. But I would like it to be dependent on the RxJava version which the library client will use, no to be explicitly provided by me in the library's build.gradle.

I don't know if that's possible because that's not the way dependencies work. Maven Transitive Dependencies explains this issue a little.

For example, you made a library and used a given version of RxJava, say, vn. It implictly means that your lib uses some features of vn that are not present in vn-1 and hopefully won't be deprecated in vn+1 and later. If a lib client were able to choose any RxJava version, it could arbitrarily pick vn-1 and your code would not work. You have a hard dependency on vn and anyone who uses your library should be aware of it.

There's no problem in providing an explicit dependency in your lib's build.gradle. In fact, listing the dependencies will help Gradle resolve the dependency graph, handle conflicts and everything. Here's a bit of what Gradle does: https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html

Finally, even if you find a way to achieve the dependency delegation to the lib client, the application can crash during runtime.

Upvotes: 1

Related Questions