Skip to content

feat: StateMachine observers#312

Merged
fgmacedo merged 2 commits intodevelopfrom
macedo/observers
Jan 11, 2023
Merged

feat: StateMachine observers#312
fgmacedo merged 2 commits intodevelopfrom
macedo/observers

Conversation

@fgmacedo
Copy link
Copy Markdown
Owner

StateMachine now supports adding observers to a running instance using StateMachine.add_observer.

Observers

Observers are a way to generically add behavior to a StateMachine without changing its internal implementation.

One possible use case is to add an observer that prints a log message when the SM runs a transition or enters a new state.

Giving the traffic_light_machine.py as example:

>>> from tests.examples.traffic_light_machine import TrafficLightMachine

>>> class LogObserver(object):
...     def __init__(self, name):
...         self.name = name
...
...     def after_transition(self, event, source, target):
...         print("{} after: {}--({})-->{}".format(self.name, source.id, event, target.id))
...
...     def on_enter_state(self, target, event):
...         print("{} enter: {} from {}".format(self.name, target.id, event))


>>> sm = TrafficLightMachine()

>>> sm.add_observer(LogObserver("Paulista Avenue"))  # doctest: +ELLIPSIS
TrafficLightMachine...

>>> sm.cycle()
Paulista Avenue enter: yellow from cycle
Paulista Avenue after: green--(cycle)-->yellow
'Running cycle from green to yellow'
The `StateMachine` itself is registered as an observer, so by using `.add_observer()` an
external object can have the same level of functionalities provided to the built-in class.

@fgmacedo fgmacedo added this to the 1.0.0 milestone Jan 11, 2023
@fgmacedo fgmacedo merged commit 762b1a9 into develop Jan 11, 2023
@fgmacedo fgmacedo deleted the macedo/observers branch January 11, 2023 21:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant