KStateMachine / kstatemachine

KStateMachine is a powerful Kotlin Multiplatform library with clean DSL syntax for creating complex state machines and statecharts driven by Kotlin Coroutines.
https://kstatemachine.github.io/kstatemachine/
Boost Software License 1.0
358 stars 21 forks source link

Lack of possibility to clear up state machine #32

Closed kwasny2 closed 2 years ago

kwasny2 commented 2 years ago

Thanks for nice implementation of state machine.

I have created some state machines which reuses some common states (objects in sealed class). I run only machine at a time, but after some user option I need to recreate whole state machine in different way. I do not see any way to clear up state machine, before reconfigure.

class ClearStatesVisitor : Visitor {
    override fun visit(machine: StateMachine) {
        visit(machine as IState)
    }

    override fun visit(state: IState) {
        state.states.forEach(::visit)
        (state.transitions as MutableSet).clear()
        (state.states as MutableSet).clear()
    }

    override fun <E : Event> visit(transition: Transition<E>) {}

  }
}

Something like that is working for me. I know it is incomplete, maybe you can extend it and add some facade function in StateMachine interface (like clearup() or something).

nsk90 commented 2 years ago

Welcome)

I have mentioned that case in docs https://github.com/nsk90/kstatemachine/wiki#do-not (do not section) In my opinion you should not reuse states in that way.

Why do you want reuse state instances across multiple machine instances? Defining state as an object is a major reason?

nsk90 commented 2 years ago

See this issue also https://github.com/nsk90/kstatemachine/issues/23 there was a same problem.

nsk90 commented 2 years ago

Done in https://github.com/nsk90/kstatemachine/releases/tag/v0.10.0

Now KStateMachine automatically detects such cases and clears object states. There is also API to clean State subclasses. And for manual usage of "cleanup" api (StateMachine::destroy() function).

Please provide feedback about this new feature if possible. Thank you.

kwasny2 commented 2 years ago

Seems to work fine, I need to play a bit more.