Skip to content

Commit

Permalink
Merge pull request #7 from RookieGameDevs/subscribe_as_decorator
Browse files Browse the repository at this point in the history
Subscribe to store with decorator

Bump version to **0.1.1**.
  • Loading branch information
duploduplo committed Feb 13, 2017
2 parents 1d93892 + f135da0 commit f5ad1b2
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
31 changes: 31 additions & 0 deletions revived/store.py
Expand Up @@ -82,6 +82,37 @@ def unsubscribe():

return unsubscribe

def subscriber(self, callback: Callable[[], None]) -> Callable[[], None]:
"""Decorator function to subscribe a function to store changes.
The subscribed function will be called every time the internal state of
the store changes.
NOTE: The decorator function will return the function itself. To
unsubscribe the callback the user should use the *unsubscribe* function
attached into the callback.
.. code:: python
# create the store object
store = Store(root_reducer)
# define and subscribe the function
@store.subscriber
def a_subscriber():
# do something!
pass
# unsubscribe the function
a_subscriber.unsubscribe()
:param callback: The callback to be subscribed. :returns: The callback
itself.
"""
unsubscribe = self.subscribe(callback)
callback.unsubscribe = unsubscribe
return callback

def dispatch(self, action: Action) -> None:
"""Dispatches an action.
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Expand Up @@ -9,7 +9,7 @@

setup(
name='revived',
version='0.1.0',
version='0.1.1',

description='Redux-inspired library in python',
long_description=long_description,
Expand Down
33 changes: 33 additions & 0 deletions tests/test_store.py
Expand Up @@ -61,6 +61,21 @@ def callback():
assert called


def test_store__dispatch__subscriber_decorator(dummy_reducer):
store = Store(dummy_reducer)

called = False

@store.subscriber
def callback():
nonlocal called
called = True

store.dispatch(Action('test'))

assert called


def test_store__unsubscribe(dummy_reducer):
called = 0

Expand All @@ -77,3 +92,21 @@ def callback():
unsubscribe()
store.dispatch(Action('test'))
assert called == 1


def test_store__unsubscribe_decorator(dummy_reducer):
store = Store(dummy_reducer)

called = 0

@store.subscriber
def callback():
nonlocal called
called += 1

store.dispatch(Action('test'))
assert called == 1

callback.unsubscribe()
store.dispatch(Action('test'))
assert called == 1

0 comments on commit f5ad1b2

Please sign in to comment.