技术问询:如何在流程内获取最终输出状态及事务流程生成的StateAndRef对象?
Hey Colin, let's tackle your two questions step by step—these are common pain points when working with state machines, so I’ll keep it practical and straightforward.
1. How to Get the Final Output State Inside a Flow
If you need to access the final state while the flow is still running (internal to the process), here are your go-to approaches:
- Use StateContext in end-state actions: When you reach a terminal state, attach an entry/exit action to it. Inside the action, you can grab the final state directly via
stateContext.getStateMachine().getState(). This gives you the fully resolved final state instance.action((stateContext) -> { State<MyStates, MyEvents> finalState = stateContext.getStateMachine().getState(); // Do something with the final state here }) - Listen for the machine stop event: Register a
StateMachineListenerand override thestateMachineStoppedmethod. This triggers right when the flow ends, and you can pull the final state from the stopped machine:@Override public void stateMachineStopped(StateMachine<MyStates, MyEvents> stateMachine) { State<MyStates, MyEvents> finalState = stateMachine.getState(); // Process the final state }
2. Accessing StateAndRef Objects When a Transactional Flow Creates New States
When your transactional flow spins up one or more new states, accessing the StateAndRef depends on how you're launching and persisting the state machine:
- Capture it directly on creation: If you're using a
StateMachineFactoryto create a new persistent state machine, thegetStateMachine()method returns aStateAndRefimmediately. This includes both the initial/new state and the unique reference ID for the machine:// Creates a new persistent state machine and returns its StateAndRef StateAndRef<MyStates, MyEvents> newStateRef = stateMachineFactory.getStateMachine(UUID.randomUUID().toString()); // After executing your transactional events State<MyStates, MyEvents> outputState = newStateRef.getState(); String machineId = newStateRef.getRef(); - Retrieve via transaction callbacks: If you're running actions within a transaction using
StateMachineTransactionManager, you can use aStateMachineCallbackto access the updatedStateAndRefonce the transaction commits. This is useful if you need to react to the new state immediately after the transaction completes:stateMachineExecutor.execute((stateMachine) -> { stateMachine.sendEvent(MyEvents.COMPLETE_TRANSACTION); return StateMachineCallback.Result.of(stateMachine.getState()); }).thenAccept(result -> { // Extract the StateAndRef from the result or state machine StateAndRef<MyStates, MyEvents> updatedStateRef = stateMachinePersister.restore(result.getStateMachine().getId()); }); - Quick note: Make sure your state machine is configured with persistence (using
StateMachinePersister) if you need to retain and retrieve theStateAndRefacross application restarts or transactions.
内容的提问来源于stack exchange,提问作者Colin
相关产品推荐
相关产品推荐

