forked from statelyai/xstate-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_workflow.py
More file actions
53 lines (41 loc) · 1.38 KB
/
Copy pathasync_workflow.py
File metadata and controls
53 lines (41 loc) · 1.38 KB
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
#!/usr/bin/env python3
"""Run a machine with an awaitable action through AsyncInterpreter."""
import asyncio
from xstate import HandlerArgs, Machine, interpret_async
async def main() -> None:
completed_jobs: list[int] = []
async def record_job(args: HandlerArgs) -> None:
await asyncio.sleep(0)
completed_jobs.append(args.event.data["job_id"])
machine = Machine(
{
"id": "async-workflow",
"initial": "idle",
"states": {
"idle": {
"on": {
"RUN": {
"target": "done",
"actions": "recordJob",
}
}
},
"done": {"type": "final"},
},
},
actions={"recordJob": record_job},
)
observed: list[object] = []
service = interpret_async(machine)
await service.start()
subscription = service.subscribe(lambda snapshot: observed.append(snapshot.value))
snapshot = await service.send({"type": "RUN", "job_id": 42})
assert snapshot.value == "done"
assert snapshot.status == "done"
assert completed_jobs == [42]
assert observed == ["idle", "done"]
subscription.unsubscribe()
await service.stop()
print("completed async job 42")
if __name__ == "__main__":
asyncio.run(main())