spring-projects / spring-statemachine

Spring Statemachine is a framework for application developers to use state machine concepts with Spring.
1.57k stars 616 forks source link

Support for Reactive Interceptors or Reactive Operations inside Interceptors #1168

Open vedantshetty opened 1 month ago

vedantshetty commented 1 month ago

I have been playing around with the state machine and have managed to utilise it to run as a workflow management system, where the state machine would persist the extended state to a database after a state transition using a preStateChange hook

    private class StateChangeInterceptor extends StateMachineInterceptorAdapter<S, E> {

        @Override
        public void preStateChange(State<S, E> state, Message<E> message,
                                   Transition<S, E> transition, StateMachine<S, E> stateMachine,
                                   StateMachine<S, E> rootStateMachine) {
          var data = getData(state, message);
           reactiveRepo.save(data).subscribe();
        }
    }

However, I noticed that the DB write needs to be blocking otherwise actions which are supposed to run after state change tend to trigger

        .state(ServiceRequestState.APPROVED,  triggerActions())

// This will run before the state change leading to weird issues like the state context being in an inconsistent stage
  private Collection<? extends Action<WorkflowState, WorkflowEvent>> triggerActions() {
    return List.of(
        Actions.errorCallingAction(notifyCustomer, handleNotificationFailure),
        Actions.errorCallingAction(logAnalytics, loggingFailure)
    );
  }

Currently my way around this is to provide an indication of the DB write being completed using the Workflow Extended State but would love to understand if there was a better way