Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
Korijn committed Nov 14, 2023
1 parent 30ae386 commit c6647ad
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
11 changes: 10 additions & 1 deletion observ/watcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ class Watcher:
"_number_of_callback_args",
"__weakref__",
]
on_created = None
on_destroyed = None

def __init__(
self,
Expand All @@ -140,7 +142,7 @@ def __init__(
) -> None:
"""
sync: Ignore the scheduler
lazy: Only reevalutate when value is requested
lazy: Only reevaluate when value is requested
deep: Deep watch the watched value
callback: Method to call when value has changed
"""
Expand Down Expand Up @@ -170,6 +172,13 @@ def __init__(
self.value = None if self.lazy else self.get()
self._number_of_callback_args = None

if Watcher.on_created:
Watcher.on_created(self)

def __del__(self):
if Watcher.on_destroyed:
Watcher.on_destroyed(self)

def update(self) -> None:
if self.lazy:
self.dirty = True
Expand Down
35 changes: 35 additions & 0 deletions tests/test_watcher_hooks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from observ import reactive, watch
from observ.watcher import Watcher


def test_watcher_hooks():
# demonstrate that watchers can be kept alive in a global registry
# using on_created and on_destroyed hooks
watchers = []

def on_created(watcher):
watchers.append(watcher)

def on_destroyed(watcher):
watchers.remove(watcher)

try:
Watcher.on_created = on_created
Watcher.on_destroyed = on_destroyed

a = reactive([1, 2])
called = 0

def _callback():
nonlocal called
called += 1

watch(lambda: len(a), _callback, sync=True)
assert called == 0
a.append(3)
assert called == 1
assert len(a) == 3

finally:
Watcher.on_created = None
Watcher.on_destroyed = None

0 comments on commit c6647ad

Please sign in to comment.