0

I need to create StateMachine to manage quests. I know how to create a state machine, but I can not use it. It's my first state machine and first project with the MongoDB.

My state machine:

@Configuration
@EnableStateMachine
class QuestStateMachineConfig : EnumStateMachineConfigurerAdapter<QuestState, QuestEvent>() {

    @Throws(Exception::class)
    override fun configure(states: StateMachineStateConfigurer<QuestState, QuestEvent>) {
        states.withStates()
                .initial(QuestState.AWAITING)

                .state(QuestState.ASSIGNED)
                .state(QuestState.MARKED_TO_REJECT)
                .state(QuestState.IN_PROGRESS)

                .end(QuestState.DONE)
                .end(QuestState.REJECTED)
    }

@Throws(Exception::class)
override fun configure(transitions: StateMachineTransitionConfigurer<QuestState, QuestEvent>) {
    transitions.withExternal()
            .source(QuestState.AWAITING).target(QuestState.ASSIGNED).event(QuestEvent.ASSIGN)
            .and()
            ...
   }

I need to create a quest with state AWAITING, next I have to modify and save it in a database when a user uses update action. How to do it? And how can I listen to onSuccess callback of this operation?

senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32
LookBad
  • 150
  • 1
  • 2
  • 18

1 Answers1

1

I need to create a quest with state AWAITING

This normally should be an Entity created in the DB. You probably want to manage this Entity's State using the state machine.

To get an instance of the SM you only need to inject it - you have already defined an instance because of @EnableStateMachine - upon starting your application an SM will be created and you can inject it where you need it.

"I have to modify and save it in a database when a user uses update action. How to do it?"

At some point the "update action" needs to translate to "update event". There's a lot of options here, depending on your needs:

  • update the quest in the DB the normal way (e.g. repository) and then move the state token in the SM to the correct state, for that user's quest (you will need some way to correlate the user, the quest and the SM instance).

  • upon "update action" - send event to the SM and let the SM update the quest in the DB and transition to a new state. This can be achieved using "actions" or listening to specific event and reacting on it using SM "listener".

how can I listen to onSuccess callback of this operation?

See StateMachineListener for starting point, also check out this answer.

hovanessyan
  • 30,580
  • 6
  • 55
  • 83