-
Notifications
You must be signed in to change notification settings - Fork 9
/
event_bus.py
32 lines (25 loc) · 1020 Bytes
/
event_bus.py
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
import asyncio
import threading
class EventBus:
_instance_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not hasattr(EventBus, "_instance"):
with EventBus._instance_lock:
if not hasattr(EventBus, "_instance"):
EventBus._instance = object.__new__(cls)
return EventBus._instance
def __init__(self):
self.listeners = {}
def add_listener(self, event_name, listener):
if not self.listeners.get(event_name, None):
self.listeners[event_name] = {listener}
else:
self.listeners[event_name].add(listener)
def remove_listener(self, event_name, listener):
self.listeners[event_name].remove(listener)
if len(self.listeners[event_name]) == 0:
del self.listeners[event_name]
def emit(self, event_name, event):
listeners = self.listeners.get(event_name, [])
for listener in listeners:
asyncio.run(listener(event))