Search code examples
javaspringspring-boothierarchicalspring-statemachine

How to get the current substate and the parent state out of the Spring Statemachine?


I am running a hierachical Spring Statemachine and - after walking through the inital transitions into state UP with the default substate STOPPED - want to use statemachine.getState(). Trouble is, it gives me only the parent state UP, and I cannot find an obvious way to retrieve both the parent state and the sub state.

The machine has states constructed like so:

    StateMachineBuilder.Builder<ToolStates, ToolEvents> builder = StateMachineBuilder.builder();


    builder.configureStates()
       .withStates()
          .initial(ToolStates.UP)
          .state(ToolStates.UP, new ToolUpEventAction(), null)
          .state(ToolStates.DOWN                
          .and()
       .withStates()
          .parent(ToolStates.UP)
          .initial(ToolStates.STOPPED)
          .state(ToolStates.STOPPED,new ToolStoppedEventAction(), null )
          .state(ToolStates.IDLE)
          .state(ToolStates.PROCESSING,
                 new ToolBeginProcessingPartAction(),
                 new ToolDoneProcessingPartAction());

    ...

    builder.build();

ToolStates and ToolEvents are just enums. In the client class, after running the builder code above, the statemachine is started with statemachine.start(); When I subsequently call statemachine.getState().getId(); it gives me UP. No events sent to statemachine before that call. I have been up and down the Spring statemachine docs and examples. I know from debugging that the entry actions of both states UP and STOPPED have been invoked, so I am assuming they are both "active" and would want to have both states presented when querying the statemachine. Is there a clean way to achieve this ? I want to avoid storing the substate somewhere from inside the Action classes, since I believe I have delegated all state management issues to the freakin Statemachine in the first place and I would rather like to learn how to use its API for this purpose.

Hopefully this is something embarrasingly obvious...

Any advice most welcome!


Solution

  • The documentation describes getStates():

    https://docs.spring.io/spring-statemachine/docs/current/api/org/springframework/statemachine/state/State.html

    java.util.Collection<State<S,E>>    getStates()
    Gets all possible states this state knows about including itself and substates.
    

    stateMachine.getState().getStates();