24. State Machine Interceptor

Instead of using a StateMachineListener interface one option is to use a StateMachineInterceptor. One conceptual difference is that an interceptor can be used to intercept and stop a current state change or transition logic. Instead of implementing full interface, adapter class StateMachineInterceptorAdapter can be used to override default no-op methods.

[Note]Note

There is one recipe Chapter 35, Persist and one sample Chapter 42, Persist which are related to use of an interceptor.

Interceptor can be registered via StateMachineAccessor. Concept of an interceptor is relatively deep internal feature and thus is not exposed directly via StateMachine interface.

stateMachine.getStateMachineAccessor()
    .withRegion().addStateMachineInterceptor(new StateMachineInterceptor<String, String>() {

        @Override
        public Message<String> preEvent(Message<String> message, StateMachine<String, String> stateMachine) {
            return message;
        }

        @Override
        public StateContext<String, String> preTransition(StateContext<String, String> stateContext) {
            return stateContext;
        }

        @Override
        public void preStateChange(State<String, String> state, Message<String> message,
                Transition<String, String> transition, StateMachine<String, String> stateMachine) {
        }

        @Override
        public StateContext<String, String> postTransition(StateContext<String, String> stateContext) {
            return stateContext;
        }

        @Override
        public void postStateChange(State<String, String> state, Message<String> message,
                Transition<String, String> transition, StateMachine<String, String> stateMachine) {
        }

        @Override
        public Exception stateMachineError(StateMachine<String, String> stateMachine,
                Exception exception) {
            return exception;
        }
    });
[Note]Note

More about error handling shown in above example, see section Chapter 26, State Machine Error Handling.