Selectively publish through the gradle maven publishing plugin only when the version doesn’t exist in the repository.

withType<PublishToMavenRepository>().configureEach {
    onlyIf {
        logger.lifecycle("Checking published version of '${publication.groupId}:${publication.artifactId}' to '${publication.version}'")
        val dep = project.dependencies.create(group = publication.groupId, name = publication.artifactId, version = publication.version)
        val conf = rootProject.configurations.detachedConfiguration(dep)
        conf.isTransitive = false
        conf.resolutionStrategy.cacheDynamicVersionsFor(0, TimeUnit.SECONDS)
        conf.resolutionStrategy.cacheChangingModulesFor(0, TimeUnit.SECONDS)
        val lenientConfiguration = conf.resolvedConfiguration.lenientConfiguration
        if (lenientConfiguration.unresolvedModuleDependencies.isEmpty()) {
            val resolved = conf.resolvedConfiguration.firstLevelModuleDependencies.first()
            logger.lifecycle("Resolved published version of '${resolved.moduleGroup}:${resolved.moduleName}' to '${resolved.moduleVersion}'")
            false
        } else {
            logger.lifecycle("No published version of '${publication.groupId}:${publication.artifactId}' resolved to '${publication.version}'")
            true
        }
    }
}
publishing {
    publications {
        create<MavenPublication>("maven") {
            groupId = "com.example.client"
            artifactId = "example-client"
            version = "0.1.0"
            from(components["java"])
        }
    }
}