forked from hiero-ledger/hiero-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubscription_handle.py
More file actions
57 lines (41 loc) · 1.51 KB
/
Copy pathsubscription_handle.py
File metadata and controls
57 lines (41 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from __future__ import annotations
import threading
from typing import Any
class SubscriptionHandle:
"""
Represents a handle to an ongoing subscription.
Calling .cancel() will signal the subscription thread to stop.
"""
def __init__(self):
self._cancelled = threading.Event()
self._thread: threading.Thread | None = None
self._call: Any | None = None
self._lock = threading.Lock()
def _set_call(self, call: Any):
"""Sets the active gRPC call so it can be cancelled."""
should_cancel = False
with self._lock:
self._call = call
if call is not None and self._cancelled.is_set():
should_cancel = True
if should_cancel:
self._call.cancel()
def cancel(self):
"""Signals to cancel the subscription."""
should_cancel = False
with self._lock:
self._cancelled.set()
if self._call is not None:
should_cancel = True
if should_cancel:
self._call.cancel()
def is_cancelled(self) -> bool:
"""Returns True if this subscription is already cancelled."""
return self._cancelled.is_set()
def set_thread(self, thread: threading.Thread):
"""(Optional) Store the thread object for reference."""
self._thread = thread
def join(self, timeout=None):
"""(Optional) Wait for the subscription thread to end."""
if self._thread:
self._thread.join(timeout)