Created
January 15, 2019 15:49
-
-
Save alirzaev/5ac73636d609d479d92c0894817dc404 to your computer and use it in GitHub Desktop.
AsyncTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AsyncTask(QRunnable): | |
class _Signals(QObject): | |
result = pyqtSignal(tuple) | |
@staticmethod | |
def _callback(args: Tuple[Callable[[Any], None], Any]): | |
fun, arg = args | |
fun(arg) | |
def __init__(self): | |
super().__init__() | |
self.result.connect(self._callback) | |
_signals = _Signals() | |
def _default_callback(*arg, **kwargs): | |
pass | |
def __init__(self, | |
routine: Callable[[], Any], | |
on_result: Callable[[Any], None] = None, | |
on_error: Callable[[Exception], None] = None): | |
super().__init__() | |
if on_result is None: | |
on_result = self._default_callback | |
self._on_result = on_result | |
if on_error is None: | |
on_error = self._default_callback | |
self._on_error = on_error | |
self._routine = routine | |
def run(self): | |
try: | |
result = self._routine() | |
self._signals.result.emit((self._on_result, result)) | |
except Exception as ex: | |
self._signals.result.emit((self._on_error, ex)) | |
def start(self, thread_pool: QThreadPool = None): | |
if thread_pool is None: | |
QThreadPool.globalInstance().start(self) | |
else: | |
thread_pool.start(self) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment