Using dependsOn on TaskProvider (configuration avoidance)

Hi,

the docs say about configuration avoidance (Task Configuration Avoidance) that I can call dependsOn on a TaskProvider without configuring the task.

Calling Provider.get() or looking up a task by name with TaskCollection.getByName(java.lang.String) will cause the task to be created and configured. Methods like Task.dependsOn(java.lang.Object…​) and ConfigurableFileCollection.builtBy(java.lang.Object…) work with TaskProvider in the same way as Task, so you do not need to unwrap a Provider for explicit dependencies to continue to work.

However, this does not work. The API does not list dependsOnas a method on TaskProvider (TaskProvider (Gradle API 8.4)). Unsurprisingly, this Java code snippet

TaskProvider<DefaultTask> myTask = this.project.getTasks().register("myTask", DefaultTask.class, task -> {
            task.setGroup("Test");
 });
 myTask.dependsOn(this.project.getTasks().getByName("build"));

results in

cannot find symbol
        myTask.dependsOn(this.project.getTasks().getByName("build"));
              ^
symbol:   method dependsOn(Task)
location: variable myTask of type TaskProvider<DefaultTask>

Am I misinterpreting the configuration avoidance manual?

1 Like

The documentation is referring to the opposite of what you’re trying to do, ie Task.dependsOn(TaskProvider).

You should not need to use a TaskProvider.dependsOn() method. Declaring task dependencies is part of configuring the task, which is what the TaskProvider is trying to avoid.
I believe this should do what you want, since there’s no need to declare the dependency on the build task unless myTask is actually realized and going to be executed. Note, I also used TaskCollection.named() to avoid prematurely realizing the build task.

TaskProvider<DefaultTask> myTask = this.project.getTasks().register("myTask", DefaultTask.class, task -> {
            task.setGroup("Test");
            task.dependsOn(this.project.getTasks().named("build"));
 });
1 Like

I was trying to create lots of similar tasks in a factory function and wanted to add dependencies for a few select tasks afterwards. I guess I have to provide the dependencies as a parameter of the factory function. Thanks for your explanation!