Observe results¶
Keep a result for the type you want to observe, subscribe a callback and refresh your application's state from that result. Read the initial state explicitly, then remove the callback when its owner stops observing. This guide assumes the installation guide and basic lookup queries. For a worked introduction, see Observe a changing selection.
Retain the result and its observer¶
Store the result on the object that uses it, and keep that object alive while observing. Results and listener registrations can be held weakly elsewhere, so subscription alone does not keep either your result or your callback owner alive. Lifetime and change notifications explains these ownership relationships.
The following complete example keeps a list of document names in an observer.
The result starts empty. Subscribe with += and call refresh() explicitly
to read the initial state, because registration does not invoke the callback.
from lookups import GenericLookup, InstanceContent, Result
class Document:
def __init__(self, name: str) -> None:
self.name = name
class DocumentList:
def __init__(self, result: Result[Document]) -> None:
self.result = result
self.names: tuple[str, ...] = ()
def refresh(self, result: Result[Document]) -> None:
self.names = tuple(sorted(document.name for document in result.all_instances()))
content = InstanceContent()
selection = GenericLookup(content)
observer = DocumentList(selection.lookup_result(Document))
observer.result.listeners += observer.refresh
try:
observer.refresh(observer.result)
print("Initial:", observer.names)
content.add(Document("report.txt"))
print("After addition:", observer.names)
content.set([])
print("After clearing:", observer.names)
finally:
observer.result.listeners -= observer.refresh
content.add(Document("chart.svg"))
print("After unsubscribe:", observer.names)
print("Current result:", tuple(document.name for document in observer.result.all_instances()))
Initial: ()
After addition: ('report.txt',)
After clearing: ()
After unsubscribe: ()
Current result: ('chart.svg',)
Here, observer retains both the result and the owner of the bound callback.
The finally block removes that callback even if a read or a content change
raises. In an application, put the corresponding removal in the owner's close
or disposal path. After unsubscribing, the result remains usable for explicit
reads.
Refresh from the callback's result¶
The result argument passed to refresh() is the observed Result[Document].
Read it again on notification: all_instances() retrieves current objects,
all_items() retrieves their descriptions, and all_classes() retrieves the
represented types. Previously returned collections do not update themselves.
Because instance reads can construct deferred members, choose item descriptions
when you only need metadata.
Treat each notification as a reason to refresh. It supplies no old/new difference, so replace the observer's names from a fresh read rather than counting additions or removals. This also handles an empty result and repeated notifications. The Result reference specifies collection and listener behaviour.
The example uses default synchronous InstanceContent notifications, so the
observer's names have refreshed when each content change returns.
Dispatch generic notifications through an executor¶
If you own the content and need to run callbacks in an executor, pass it to
InstanceContent(notify_in=executor). Set this up when creating the content,
before consumers subscribe to its results.
The following example uses a queue to pass document names from the callback to the owning thread. It reads the initial state before changing the content, then waits for the executor's submitted work before removing the callback. Keep the result and callback alive through that wait, and stop changing the content before shutting down its notification executor.
from concurrent.futures import ThreadPoolExecutor
from queue import SimpleQueue
from lookups import GenericLookup, InstanceContent, Result
class Document:
def __init__(self, name: str) -> None:
self.name = name
executor = ThreadPoolExecutor(max_workers=1)
content = InstanceContent(notify_in=executor)
selection = GenericLookup(content)
result = selection.lookup_result(Document)
views: SimpleQueue[tuple[str, ...]] = SimpleQueue()
def record_view(changed: Result[Document]) -> None:
views.put(tuple(sorted(document.name for document in changed.all_instances())))
result.listeners += record_view
try:
with executor:
print("Initial:", tuple(document.name for document in result.all_instances()))
content.add(Document("report.txt"))
finally:
result.listeners -= record_view
while not views.empty():
print("Queued view:", views.get_nowait())
The program prints an empty initial view followed by a queued view containing
report.txt. With several changes, a delayed callback can read membership that
already includes later changes, so use the queue to refresh a view rather than
to record every intermediate state.
For a UI, drain the queue on the UI thread through your framework's dispatch mechanism. The notification executor runs callbacks, but does not coordinate other lookup access or marshal widget updates to the UI thread.