Tinder / StateMachine

A Kotlin and Swift DSL for finite state machine
Other
1.96k stars 128 forks source link

OnEnter not called for initialState #35

Open dariush-fathie opened 3 years ago

dariush-fathie commented 3 years ago

Thank you for your amazing library I have a problem with onEnter at initialState.

It's my code :

   val machine = StateMachine.create<State, Event, SideEffect> {
   initialState(State.INIT)

   state<State.INIT> {
      onEnter {
         println("onEnter INIT")
      }

      on<Event.E1> {
         println("onE1 INIT")
         transitionTo(State.INITIALIZED)
      }
   }

   state<State.INITIALIZED> {
      onEnter {
         println("enter initialized")
      }

      on<Event.E1> {
         transitionTo(State.FINAL)
      }

      onExit {
         println("exit initialized")
      }
   }

   state<State.FINAL> {
      onEnter {
         println("onFinal")
      }
   }

}

machine.transition(Event.E1)
machine.transition(Event.E1)

sealed class State {
   object INIT : State()
   object INITIALIZED : State()
   object FINAL : State()
}

sealed class Event {
   object E1 : Event()
}

sealed class SideEffect {

}

Result:

onE1 INIT enter initialized exit initialized onFinal

dtbullock commented 3 years ago

I wouldn't expect an 'initial' state to be entered? That would imply that it is transitioning from some other state, and that wouldn't make it the initial state. So maybe you just need an extra state to be the 'initial nothing state'?

Eg. My app's state-machine starts in a 'Disconnected' state. It doesn't take a transition to get there ... that's the correct state for the state-machine to be in once it is built (it has to be in some state already!).