KStateMachine / kstatemachine

KStateMachine is a Kotlin DSL library for creating state machines and statecharts.
https://kstatemachine.github.io/kstatemachine/
Boost Software License 1.0
340 stars 19 forks source link

Transitions #27

Closed asad-awadia closed 2 years ago

asad-awadia commented 2 years ago
        addInitialState(GreenState) {
            // Add state listeners
            onEntry { println("Enter green") }
            onExit { println("Exit green") }

            // Setup transition
            transition<NextEvent> {
                targetState = YellowState
                // Add transition listener
                onTriggered { println("Transition triggered") }
            }
        }

In this example is the onTriggered done before the state is moved to Yellow?

What happens if the onTriggered fails/crashes/throws an exception?

@nsk90

nsk90 commented 2 years ago

1) Yes transition callback is triggered first, than state will switch to Yellow and state notifications (onEntry/onExit) will be triggered, I think this is the mostly expected order.

This is a place where notification is triggered: https://github.com/nsk90/kstatemachine/blob/abba5fcca294b6d1bea58f4fefd4e601ac045d28/kstatemachine/src/main/kotlin/ru/nsk/kstatemachine/StateMachineImpl.kt#L114

But I do not think that you should rely on callback execution order, please let me know your use case if you have to.

2) All callback functions (for notifications) are expected to be "nothrow". Currently library does not try to handle such exceptions. It is easy to add some kind of logging handler, but I am not sure that this is necessary. If it happens and exception will be thrown by your code from callback you will see it coming from processEvent() function. The Machine state is undefined if it happens.

asad-awadia commented 2 years ago

Ok ok - will need to test things out

Thank you