Issue
Let's say I have a function that updates some internal states of the application:
def on_change(*args, **kwargs):
pass # some compute intensive state change
This function can run up to hundred times a second (due to many mousewheel events triggering the update) - I would only like to execute the above function once and only the last call should be executed.
What is the best design pattern for managing such a situation? The only way I can think of is spawning a separate thread for each on_change call and share a variable between them, but this sounds overly messy...
Thanks!
Solution
class Waiter:
def __init__(self):
self.args = ()
self.kwargs = {}
self.changed = False
def on_change(self, *args, **kwargs):
# This is the event handler
# It does nothing but save the latest arguments
self.args = args
self.kwargs = kwargs
self.changed = True
def tick(self):
# Call this function once per second, or whatever
if self.changed:
# Do your updates, using self.args and self.kwargs
self.changed = False
Since you mentioned mouse events you are evidently writing a GUI application. All GUI engines, in my experience, have timers and the ability to call functions on a periodic basis. Use that capability to call tick periodically.
Answered By - Paul Cornelius
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.