lucywang000 / clj-statecharts

State Machine and StateCharts for Clojure(Script)
https://lucywang000.github.io/clj-statecharts/
Eclipse Public License 1.0
229 stars 15 forks source link

Making actions aware of the service that wraps the FSM #18

Open p-himik opened 6 months ago

p-himik commented 6 months ago

I'm experimenting with clj-statecharts for the purpose of using it with LibGDX. A common pattern there is for a screen instance to react to an action of a user by setting the next screen for the game instance. In Java (at least, in the code that I've seen), they do it by passing the game instance all over the place and making every screen create an instance of the next screen, which I'm not a fan of. An obvious solution is to create an FSM with a service where some states have corresponding screens set up in their :entry action. Those screens then would ask the service to transition to the right next state.

However, there's no convenient way of letting the actions know about the service. Every action has two arguments - state and event. Putting the instance of a service into state at the user level is not possible without writing a custom service since the transition-opts are set at service instantiation time, when the service itself is not ready. Putting the instance into event is doable but cumbersome since it has to be done on every event transition.

Would it make sense to add a :_service key to the state map when running actions?

p-himik commented 6 months ago

Just realized that a better workaround is to have the very first :entry action take the service from its event and put it into the state, and make all subsequent actions take the service from there.