Is there an easy way to clean subprojects conditionally?

In my project we have a single UI subproject, depending on several service subprojects. The UI subprojects changes relatively often, whereas the service subprojects change rarely in comparison.

We need to often run

gradle clean test

In particular whenever switching git development branches, because of stale class files after the switch.

It would be nice if there was a way of telling gradle to run clean only in all subprojects in which changes have happened to source sets. I know that we can run

gradle :uiproject:clean test

but that is less generic. I can also define a task as an alias, but I wonder whether anyone found a nicer solution.

EDIT: For consistency, a subproject should be cleaned if it has changes to it’s source set, or dependencies have changed…