diff --git a/gotify_tray/gui/MainApplication.py b/gotify_tray/gui/MainApplication.py index c839e06..817d220 100644 --- a/gotify_tray/gui/MainApplication.py +++ b/gotify_tray/gui/MainApplication.py @@ -166,16 +166,25 @@ class MainApplication(QtWidgets.QApplication): else: self.gotify_client.stop(reset_wait=True) - def application_selection_changed_callback( - self, item: ApplicationModelItem | ApplicationAllMessagesItem - ): + def abort_get_messages_task(self): + """ + Abort any tasks that will result in new messages getting appended to messages_model + """ + aborted_tasks = [] + for s in ["get_application_messages_task", "get_messages_task"]: + if task := getattr(self, s, None): + task.abort() + aborted_tasks.append(task) + + for task in aborted_tasks: + task.wait() + + def application_selection_changed_callback(self, item: ApplicationModelItem | ApplicationAllMessagesItem): + self.abort_get_messages_task() self.messages_model.clear() if isinstance(item, ApplicationModelItem): - self.get_application_messages_task = GetApplicationMessagesTask( - item.data(ApplicationItemDataRole.ApplicationRole).id, - self.gotify_client, - ) + self.get_application_messages_task = GetApplicationMessagesTask(item.data(ApplicationItemDataRole.ApplicationRole).id, self.gotify_client) self.get_application_messages_task.message.connect(self.messages_model.append_message) self.get_application_messages_task.start() diff --git a/gotify_tray/tasks.py b/gotify_tray/tasks.py index 108673c..04bb4cd 100644 --- a/gotify_tray/tasks.py +++ b/gotify_tray/tasks.py @@ -26,11 +26,18 @@ class BaseTask(QtCore.QThread): def __init__(self): super(BaseTask, self).__init__() self.running = False + self._abort = False @abc.abstractmethod def task(self): ... + def abort(self): + self._abort = True + + def abort_requested(self) -> bool: + return self._abort + def run(self): self.running = True try: @@ -111,6 +118,8 @@ class GetApplicationMessagesTask(BaseTask): self.error.emit(result) else: for message in process_messages(result.messages): + if self.abort_requested(): + return self.message.emit(message) # Prevent locking up the UI when there are a lot of messages ready at the same time @@ -133,6 +142,8 @@ class GetMessagesTask(BaseTask): self.error.emit(result) else: for message in process_messages(result.messages): + if self.abort_requested(): + return self.message.emit(message) time.sleep(0.001) self.success.emit(result)