io.smooth.constraint.ConstraintsService.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of constraints Show documentation
Show all versions of constraints Show documentation
A suite of libraries made to help ease developer's life
The newest version!
package io.smooth.constraint
import io.smooth.constraint.resolution.ConstraintResolution
import io.smooth.constraint.resolution.ConstraintResolutionService
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import javax.inject.Provider
import kotlin.reflect.KClass
class ConstraintsService {
private val resolutionService = ConstraintResolutionService()
suspend fun check(
vararg constraints: Constraint<*>
): Flow = flow {
if (constraints.isNullOrEmpty()) {
emit(ConstraintsMet(constraints))
return@flow
}
val constraintsStatuses: MutableMap, ConstraintStatus> = mutableMapOf()
constraints.forEach { constraint ->
resolutionService.addConstraintsResolutions(constraint)
constraint.check().collect { status ->
constraintsStatuses[constraint] = status
val result = checkConstraints(constraints, constraintsStatuses)
this.emit(result)
}
}
}
suspend fun , CR : ConstraintResolution> resolve(
constraint: C,
resolution: CR
) {
resolution.resolve(constraint)
}
suspend fun , CR : ConstraintResolution> getDetails(
constraint: C,
resolution: CR
) = resolution.getDetails(constraint)
suspend fun addConstraintsResolutions(
constraintClass: KClass>,
resolutions: List, *>>>
) {
resolutionService.addConstraintsResolutions(constraintClass, resolutions)
}
suspend fun > addConstraintResolution(
constraintClass: KClass,
resolutionProvider: Provider>
) {
resolutionService.addConstraintResolution(constraintClass, resolutionProvider)
}
suspend fun > getConstraintResolutions(constraintClass: KClass): List>>? =
resolutionService.getConstraintResolutions(constraintClass)
private fun checkConstraints(
constraints: Array>,
constraintsStatuses: MutableMap, ConstraintStatus>
): ConstraintResult {
if (constraintsStatuses.size != constraints.size) return ConstraintsPending(constraints)
val blockingConstraints: MutableList> = arrayListOf()
constraintsStatuses.forEach {
if (it.value == ConstraintStatus.CONSTRAINT_NOT_MET) {
blockingConstraints.add(it.key)
}
}
return if (blockingConstraints.isEmpty()) ConstraintsMet(constraints)
else ConstraintsNotMet(constraints, blockingConstraints)
}
companion object {
private var instance: ConstraintsService? = null
fun getInstance(): ConstraintsService {
if (instance == null) {
instance = ConstraintsService()
}
return instance!!
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy