matthewp / robot

🤖 A functional, immutable Finite State Machine library

Home Page:https://thisrobot.life

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add API to get next possible transitions

pke opened this issue · comments

I am building an API server to serve xState statecharts. For that I need to know which events are generally possible in the current state of the machine.
xState has a way to tell me with nextEvents. It seems robot does not provide such view on the state yet?
In xState I can also try to perform a state change without actually changing the state machines current state using service.machine.transition(current, event).changed
Is something like that possible with robot?

I'd like to add robot support to my API server.

Hey @pke! You can get the current state's transitions with machine.state.value.transitions.

As for your second question, there's not a super easy way to do that at the moment. I think this will likely work:

let tempService = Object.create(service);
tempService.send(event);

That should send a transition through a new service without mutating your "real" service object. Not pretty but I think it'll likely work. Making that part of the API immutable is one of the things I want the most.

Thanks, then I can add some sample statechars to my Statecharts API Server project. It currently serves xState charts and it will be a nice exercise to add robot support.
Whats your recommendation to persist and rehydrate robot statecharts?

Save machine.current to localStorage or wherever and then use the initial argument to create it next time: https://thisrobot.life/api/createMachine.html#initial

@matthewp I don't know if what I'm seeing is directly related to lit-robot or not (and can create a new issue in that repo if so), but when I use this.machine.state.value.transitions it always returns an empty object. I'm futzing around with it here if you have thoughts on something I might just be doing plain wrong.

transitions is a Map, I think that's just JSON.stringify not being able to serialize maps. If you need an Object you should be able to do Object.fromEntries(this.machine.state.value.transitions)

😱 how silly of me! That should do the trick when I’m back in front of this. Thanks!

No problem, it's possible that it was an object in an earlier version and I changed it. I'm too lazy to look at the blame but I think that's true.

Going to close as there's nothing to change here.