jvmMain.JvmValidations.kt Maven / Gradle / Ivy
package io.kform
import java.util.*
import java.util.concurrent.CompletionStage
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.future.await
/** [Validation] more easily implementable from Java. */
public abstract class JvmValidation : Validation() {
public override var dependsOnDescendants: Boolean = false
protected set
public abstract override fun ValidationContext.validate(): Flow
}
/** Synchronous [validation][Validation] more easily implementable from Java. */
public abstract class SyncValidation : JvmValidation() {
/**
* Synchronous implementation of [ValidationContext.validate]. Validation issues should be added
* to [issues].
*/
public abstract fun validate(context: ValidationContext, issues: MutableList)
final override fun ValidationContext.validate(): Flow {
val issues = ArrayList(10)
validate(this, issues)
return issues.asFlow()
}
}
/** Asynchronous [validation][Validation] more easily implementable from Java. */
public abstract class AsyncValidation : JvmValidation() {
/**
* Asynchronous implementation of [ValidationContext.validate] returning a completion stage.
* Validation issues should be added to [issues] (which is a synchronized list).
*/
public abstract fun validate(
context: ValidationContext,
issues: MutableList
): CompletionStage?
final override fun ValidationContext.validate(): Flow = flow {
val issues = Collections.synchronizedList(ArrayList(10))
validate(this@validate, issues)?.await() ?: return@flow
for (issue in issues) {
emit(issue)
}
}
}