Publish custom task's optional output file only if the file exists

Hello, I have a custom task that may or may not generate a file. I would like to publish this output file when it is generated, but I didn’t find how to publish an optional artifact. My current solution is to add the artifact in the “doLast” method of my custom task:

myTask.doLast(it → {
File myFile = myTask.getArtifactFile().getAsFile().get();
if (myFile.exists()) {

And the “publish” task explicitly depends on my custom task. Is there a better way to include an optional output file of a task in a MavenPublication?