-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathStdLibMinimalSealedClassesSample.kt
61 lines (50 loc) · 1.79 KB
/
StdLibMinimalSealedClassesSample.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* Author: Mikhail Fedotov
* Github: https://github.com/KStateMachine
* Copyright (c) 2024.
* All rights reserved.
*/
package ru.nsk.samples
import ru.nsk.kstatemachine.event.Event
import ru.nsk.kstatemachine.state.*
import ru.nsk.kstatemachine.statemachine.createStdLibStateMachine
import ru.nsk.kstatemachine.statemachine.processEventBlocking
import ru.nsk.kstatemachine.transition.onTriggered
import ru.nsk.samples.StdLibMinimalSealedClassesSample.States.*
import ru.nsk.samples.StdLibMinimalSealedClassesSample.SwitchEvent
private object StdLibMinimalSealedClassesSample {
object SwitchEvent : Event
sealed class States : DefaultState() {
object GreenState : States()
object YellowState : States()
object RedState : States(), FinalState // Machine finishes when enters final state
}
}
/**
* This sample uses KStateMachine only with Kotlin Standard library (without Kotlin Coroutines library).
*/
fun main() {
// Create state machine and configure its states in a setup block
val machine = createStdLibStateMachine {
addInitialState(GreenState) {
// Add state listeners
onEntry { println("Enter $this") }
onExit { println("Exit $this") }
// Setup transition
transition<SwitchEvent> {
targetState = YellowState
// Add transition listener
onTriggered { println("Transition triggered") }
}
}
addState(YellowState) {
transition<SwitchEvent>(targetState = RedState)
}
addFinalState(RedState)
onFinished { println("Finished") }
}
// Now we can process events
machine.processEventBlocking(SwitchEvent)
machine.processEventBlocking(SwitchEvent)
check(machine.isFinished)
}