ztnel / myosin

Lightweight state management engine for embedded linux
https://myosin.readthedocs.io
MIT License
0 stars 0 forks source link

Support Decorators for State Subscription #14

Open ztnel opened 2 years ago

ztnel commented 2 years ago

Because the state management systems primary api is implemented as a context manager it would make sense that state subscription callbacks can be wrapped by a decorator.

Current Implementation

In the consumer init you register a subscription to an async callback using the context manager:

class Runner:
    def __init__(self) -> None:
        self.username = ""
        with State() as state:
            state.subscribe(User, self.update)

    async def update(self, usr: User) -> None:
        self.username = usr.name

Proposed Alternate Syntax

The alternative syntax is significantly cleaner:

class Runner:
    def __init__(self) -> None:
        self.username = ""

    @state.subscribe(User)
    async def update(self, usr: User) -> None:
        self.username = usr.name
ztnel commented 2 years ago

While this syntax is cleaner from a syntactic perspective, the implementation is significantly more complex. It will probably involve a module loader and extracting all functions with the subscribe decorator to be loaded into the subscriber callback.