KStateMachine / kstatemachine

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

An API question - guard based on event parameter #69

Closed sorokod closed 1 year ago

sorokod commented 1 year ago

I have a MyDataEvent that is a DataEvent<Int>. A transition should occur only if data is non negative (for example).

It looks like a guard thing but I don't see a way of accessing the event data from a guard.

transition<MyDataEvent> {
    guard = { event.data >= 0 } // ????
    targetState = SomeState
}

Am I missing something? Is there a better approach?

nsk90 commented 1 year ago

Hello! Check out this sample https://github.com/nsk90/kstatemachine/blob/master/samples/src/commonMain/kotlin/ru/nsk/samples/TypesafeTransitionSample.kt

It looks very close to your code, but if you use DataState/DataEvent api, I assume that you should use dataTransition instead of simple transition function.

sorokod commented 1 year ago

Ok, interestingly in this case the targetState must be a DataState. Something like:

dataTransition<MyDataEvent, Int>  {
    guard = { event.data >=0 }
    targetState = MyDataState
}

There may be use cases where this is not necessary.

nsk90 commented 1 year ago

Yes, DataEvent is designed to be used in a couple with DataState. That is the way how I can guarantee at compile time that state receives expected data. If you don't need compile time guarantee or this API does not completely fit your use case, you can subclass simple Event, not DataEvent.

like this:

data class MyEvent(val data: Int) : Event

This block should work in this case guard = { event.data >= 0 }

sorokod commented 1 year ago

Nice, that is what I was looking for.

nsk90 commented 1 year ago

.