mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-06-17 23:35:14 +00:00
61 lines
2.2 KiB
Kotlin
61 lines
2.2 KiB
Kotlin
package dev.inmo.micro_utils.fsm.common
|
|
|
|
import dev.inmo.micro_utils.common.*
|
|
import kotlinx.coroutines.*
|
|
import kotlinx.coroutines.sync.withLock
|
|
|
|
/**
|
|
* This extender of [StatesMachine] interface declare one new function [updateChain]. Realizations of this interface
|
|
* must be able to perform update of chain in internal [StatesManager]
|
|
*/
|
|
interface UpdatableStatesMachine<T : State> : StatesMachine<T> {
|
|
/**
|
|
* Update chain with current state equal to [currentState] with [newState]. Behaviour of this update preforming
|
|
* in cases when [currentState] does not exist in [StatesManager] must be declared inside of realization of
|
|
* [StatesManager.update] function
|
|
*/
|
|
suspend fun updateChain(currentState: T, newState: T)
|
|
}
|
|
|
|
open class DefaultUpdatableStatesMachine<T : State>(
|
|
statesManager: StatesManager<T>,
|
|
handlers: List<CheckableHandlerHolder<in T, T>>,
|
|
) : DefaultStatesMachine<T>(
|
|
statesManager,
|
|
handlers
|
|
), UpdatableStatesMachine<T> {
|
|
protected val jobsStates = mutableMapOf<Job, T>()
|
|
|
|
override suspend fun performStateUpdate(previousState: Optional<T>, actualState: T, scope: CoroutineScope) {
|
|
statesJobsMutex.withLock {
|
|
if (compare(previousState, actualState)) {
|
|
statesJobs[actualState] ?.cancel()
|
|
}
|
|
val job = previousState.mapOnPresented {
|
|
statesJobs.remove(it)
|
|
} ?.takeIf { it.isActive } ?: scope.launch {
|
|
performUpdate(actualState)
|
|
}.also { job ->
|
|
job.invokeOnCompletion { _ ->
|
|
scope.launch {
|
|
statesJobsMutex.withLock {
|
|
statesJobs.remove(
|
|
jobsStates[job] ?: return@withLock
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
jobsStates.remove(job)
|
|
statesJobs[actualState] = job
|
|
jobsStates[job] = actualState
|
|
}
|
|
}
|
|
|
|
protected suspend fun compare(previous: Optional<T>, new: T): Boolean = previous.dataOrNull() != new
|
|
|
|
override suspend fun updateChain(currentState: T, newState: T) {
|
|
statesManager.update(currentState, newState)
|
|
}
|
|
}
|