#Is it correct to assume that a compound state's final state is truly final?

1 messages · Page 1 of 1 (latest)

willow lintel
#

Please review this code snippet:

const parentMachine = createMachine({
  predictableActionArguments: true,
  id: 'parent',
  initial: 'nested',
  states: {
    nested: {
      initial: 'idle',
      states: {
        idle: {},
        done: {
          type: 'final',
        },
      },
      on: {
        Go: '.done',
        Reset: '.idle',
        GoOutside: 'outside',
      },
    },
    outside: {},
  },
});

I initially believed that the transition from nested.done to nested.idle would be restricted since nested.done is a final state.
Similarly, I expected that the GoOutside event could trigger a transition from nested.done to outside since nested.done is a locally final state, and it shouldn't affect transitions between parent states.

However, I noticed that both transitions are possible.
Surprisingly, the Reset event can transition from nested.done to nested.idle. Now, I'm questioning my understanding of the final state concept. What am I overlooking?

gilded verge
#

Good question! so a final state has two different behaviors in a statechart:

(1) if a top-level final state is entered then the statechart stops running, cleans itself up, and emits a done event.

(2) if a final state is entered in a compound state then a done event is generated by the statechart. Final states are not allowed to have transitions on them, but they do inherit the transitions defined on parent states.

2 is why the Reset event transitions out of a final state without causing the nested state to be re-entered.

willow lintel
#

Thanks for your kind reply!
These are the alternative approaches that came to my mind

  • Make a separated child machine for nested state and invoke it
  • Set all the transitions undefined in the nested final state

Do we have better solutions? I would like to know how to do the second approach in a neat way.

gilded verge
#

may I ask what you are tring to model?

willow lintel
#

I was refactoring my old QR code scanner.

gilded verge
#

right, are you able to share all or part of the statechart that pertain to your question?

#

im happy to take a look and see if there is a alternative way to model it!

willow lintel
#

Thank you very much for your suggestion!
However, I'm currently in the middle of refactoring process, and removing all the domain-specific code will require some time.
Once I complete the refactoring, I'll ask you again!