Spring Statemachine State Actions vs Transition actions

2.7k Views Asked by At

Spring statemachine provides following type of actions. Can someone please explain me which type of action should be used in which scenario? And, If an action fails then does statemachine move to next state or not?

  1. Event action - Action attached to a transition when an event is generated.
  2. State entry action
  3. State exit action
  4. State DoAction

My scenario is that when statemachine comes in S1 state it needs to perform some operation and if its successful then only go into S2. Should it be state action or event action?

S1--->S2

2

There are 2 best solutions below

0
On BEST ANSWER
  1. Event action: This is most the common case, you have StateA and want to move to StateB when EventAB is received. Action will be fired if the machine is on StateA and you submit the EventAB to it. Its possible (and optional) to provide an error action to do personal processing in case exception is throw from regular action

  2. State entry action: Action will be hit every time machine reaches specified states. I've seen people using it to provide Initial state custom behavior

  3. Same as above, but this is hit on every state exit

  4. I haven't used this one, but according to the documentation (snippet below), its similar to state entry (in case you provide single action), but can also work with an error action.

update on this: I read in the UML specification that state do can also be used for an action that you want to be continuously happening while machine in that state

The caveats is that actions can be attached to transitions (i.e from A to B, or from B to A), so it matters the FROM and TO, while actions configured for specific state do not care where it came from, but solely related to state enter/exit

//Specify a state S with state behaviour Action. Currently synonym for state(Object, Action).
StateConfigurer<S, E> stateDo(S state, Action<S, E> action);

In case an entry/transition action fails (and you're not in a choice pseudo-state), machine stays in the same state (doesn't move).

For your scenario, it depends, is S1 initial state? if that is, you might need a state action. Otherwise, transition action between S1 -> S2 is just fine.

0
On

I am starting to learn Spring State Machine and just wanted to add that apparently State actions are not treated the same way as Entry/Exit actions.

The following is part of the documentation Reference:

State Actions State actions are run differently compared to entry and exit actions, because execution happens after state has been entered and can be cancelled if state exit happens before a particular action has been completed.