4

I have this simple state machine configuration :

@Configuration 
@EnableStateMachine 
public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapter<State, Boolean> {

    @Override
    public void configure(StateMachineStateConfigurer<State, Boolean> states) throws Exception {
        states.withStates()
                .initial(State.INITIAL)
                .states(EnumSet.allOf(State.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<State, Boolean> transitions) throws Exception {
        transitions
            .withExternal() 
                .source(State.INITIAL)
                .target(State.HAS_CUSTOMER_NUMBER)
                .event(true)
                .action(retrieveCustomerAction()) 
                // here I'd like to retrieve the customer from this action, like:
                // stateMachine.start();
                // stateMachine.sendEvent(true);
                // stateMachine.retrieveCustomerFromAction();
            .and()
            .withExternal()
                .source(State.INITIAL)
                .target(State.NO_CUSTOMER_NUMBER)
                .event(false)
                .action(createCustomerAction()); 
                // here I'd like to send the customer instance to create, like:
                // stateMachine.start();
                // stateMachine.sendEvent(false);
                // stateMachine.sendCustomerToAction(Customer customer);
    }

    @Bean
    public Action<State, Boolean> retrieveCustomerAction() {
        return ctx -> System.out.println(ctx.getTarget().getId());
    }

    @Bean
    public Action<State, Boolean> createCustomerAction() {
        return ctx -> System.out.println(ctx.getTarget().getId());
    }

}

Is it possible to improve actions definition to be able to interact with them with dynamics parameters ? How could I add consumer or provider behaviors to those actions ?

louis amoros
  • 2,418
  • 3
  • 19
  • 40

1 Answers1

1

Is it possible to improve actions definition to be able to interact with them with dynamics parameters?

Yes, it's possible. You can store the variables in the context store and retrieve then wherever you want.

public class Test {

  @Autowired
  StateMachine<State, Boolean> stateMachine;

  public void testMethod() {

    stateMachine.getExtendedState().getVariables().put(key, value);
    stateMachine.start();
    stateMachine.sendEvent(true);
  }
}

And You can retrieve this value from the context using the key. Suppose the value was of the type String then it can be retrieved like this:-

    @Bean
    public Action<State, Boolean> retrieveCustomerAction() {
        return ctx -> {
        String value = ctx.getExtendedState().get(key, String.class);
        // Do Something
        };
    }

For more you can refer the link and this

How could I add consumer or provider behaviors to those actions?

Can you elaborate more on this question

Vakul Gupta
  • 90
  • 1
  • 9