KStateMachine / kstatemachine

KStateMachine is a Kotlin DSL library for creating state machines and statecharts.
https://kstatemachine.github.io/kstatemachine/
Boost Software License 1.0
339 stars 19 forks source link

onEntry with Transition or Conditional Transition without Event #73

Closed joelk-2023 closed 5 months ago

joelk-2023 commented 10 months ago

Thanks for this library!

We have a use case where the initial state is "Loading", it then executes a business condition function to determine which nested state to transition to. Currently this is implemented using something like this:

initialState("Loading") {
   transitionConditionally<ContinueEvent> {
   direction = {
      if (businessCondition()) {
          targetState(firstState)
       } else {
          targetState(secondState)
       }
      }
   }
}.onEntry(once = true) {
     // advance to transitionConditionally
    machine.processEvent(ContinueEvent)
}

SCXML shows that the Transition Event is optional. Is there a better way to enforce that a transition must be executed immediately upon entry as a default Transition?

nsk90 commented 10 months ago

Hello, you are welcome) Your case looks like ChoiseState, have you tried it? https://nsk90.github.io/kstatemachine/#:~:text=in%20machine%20behaviour.-,Choice%20state,-Choice%20state%20allows

joelk-2023 commented 9 months ago

How can a ChoiceState be used as an initial state, and will it emit the state to the flow? Can you show an example? Thanks!

nsk90 commented 9 months ago

Oops looks that choiceState as initial state is not supported. Here is a test: https://github.com/nsk90/kstatemachine/blob/b9c09c9e9b82015199b740680562dd79e612f745/tests/src/commonTest/kotlin/ru/nsk/kstatemachine/ChoiceStateTest.kt#L59 I dont remember why, should check the reason.

nsk90 commented 8 months ago

Currently the library, does not resolve such complex redirections (like joinState) on entering into initial state path. As this may lead to purely configured machine structure. I will see if I can implement this in new version. I recommend using your current solution as workaround.

nsk90 commented 5 months ago

now ChoiceState can be used in initial state path. The StateMachine will check it and redirect to calculated state.