https://github.com/weilueluo/tsm4j
A tiny, in-memory, zero dependency state machine library
https://github.com/weilueluo/tsm4j
java state-machine
Last synced: 9 months ago
JSON representation
A tiny, in-memory, zero dependency state machine library
- Host: GitHub
- URL: https://github.com/weilueluo/tsm4j
- Owner: weilueluo
- License: apache-2.0
- Created: 2024-02-27T19:20:39.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2024-07-21T15:07:00.000Z (almost 2 years ago)
- Last Synced: 2025-04-07T23:41:27.220Z (about 1 year ago)
- Topics: java, state-machine
- Language: Java
- Homepage:
- Size: 170 KB
- Stars: 26
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# tsm4j
A tiny, in-memory, zero dependency state machine library
## Install
### Gradle
```
implementation 'com.tsm4j:tsm4j:1.1.0'
```
### Maven
```xml
com.tsm4j
tsm4j
1.1.0
```
## Usage
### Example
An example of defining and running a state machine:
```java
StateMachine stateMachine = StateMachineBuilder.from(TestState.class)
.addTransition(TestState.HUNGRY, TestState.MAKE_FOOD)
.addTransition(TestState.MAKE_FOOD, TestState.FOOD_IS_READY)
.addTransition(TestState.FOOD_IS_READY, TestState.EAT_FOOD)
.addTransition(TestState.EAT_FOOD, TestState.FULL)
.build();
assertThat(stateMachine.send(TestState.HUNGRY).reached(TestState.FULL)).isTrue();
```
You can bind a listener which is called whenever some state(s) is reached
```java
StateMachine stateMachine = StateMachineBuilder.from(TestState.class)
.addTransition(TestState.NO_FOOD, TestState.MAKE_FOOD)
.addListener(TestState.MAKE_FOOD, context -> {
System.out.println("making food...");
context.queue(TestState.FOOD_IS_READY);
})
.addListener(debugLoggingListener())
.build();
assertThat(stateMachine.send(TestState.NO_FOOD).reached(TestState.FOOD_IS_READY)).isTrue();
```
### More Examples
see tsm4j/test.
## About the older version
In short, it was going in the wrong direction, we should separate state machine from action.
## Contributing
Feel free to open up an issue for a feature request, bug report, or pull request.