Generate task graph on the fly

Is there a way to do the following with Gradle?

I have 3 tasks: calc, choiceA and choiceB. Task “calc” does some calculations and puts the value somewhere. It can be an ext, a local variable or an external file, it doesn’t matter.

Based on the value of this output, either choiceA or choiceB will run, but not both.

The problem I see is that the graph is generated even before the “calc” start begins and I can’t seem to change it afterwards. If inside the “calc” task I write calc.finalizedBy(choiceA) then nothing will happen. I also tried task choiceA { enabled = valueSetByCalc } but this also doesn’t work. The value of enabled cannot be changed once the graph execution begins.

How can I solve this problem?

Some examples that don’t work:

task calc { }
task choiceA { }
task choiceB { }

calc.doLast {
    calc.finalizedBy(choiceA)
}

Using the enabled property:

project.ext {
    runChoiceA = false
}

tasks.register("calc") {
    if (1 < 2) {
        project.ext.runChoiceA = true
    }
}
tasks.register("choiceA") {
    enabled = project.ext.runChoiceA
}
tasks.register("choiceB") {
    enabled = !project.ext.runChoiceA
}

Modifying the graph doesn’t do anything:

gradle.taskGraph.whenReady {
  tasks.each {
      if (it.name == 'choiceA') {
          it.enabled = true
      } else if (it.name == 'choiceA') {
          it.enabled = false
      } else
  }
}

I figured it out. The solution is to use onlyIf and have it read the property.

project.ext {
    runA = false
    runB = false
}

task calc { }

task choiceA { 
  onlyIf { project.ext.runA }
  dependsOn(calc)
}
task choiceB { 
  onlyIf { project.ext.runB }
  dependsOn(calc)
}

calc.doLast {
    if (1 < 2) {
      project.ext.runA = true
    } else {
      project.ext.runB = true
    }
}