Common: Modify PyPubSubEventQueue to pass publisher in constructor

This commit is contained in:
Shreya Malviya 2022-08-09 14:31:44 +05:30
parent 00b62dc1a9
commit d190f220f7
1 changed files with 16 additions and 15 deletions

View File

@ -1,35 +1,36 @@
from typing import Any, Callable
from pubsub import pub
from common.events import AbstractEvent
from .i_event_queue import IEventQueue
class PyPubSubEventQueue(IEventQueue):
@staticmethod
def subscribe_all(subscriber: Callable[[AbstractEvent], None]):
pub.subscribe(listener=subscriber, topicName=pub.ALL_TOPICS)
def __init__(self, pypubsub_publisher):
self._pypubsub_publisher = pypubsub_publisher
@staticmethod
def subscribe_type(event_type: AbstractEvent, subscriber: Callable[[AbstractEvent], None]):
def subscribe_all(self, subscriber: Callable[[AbstractEvent], None]):
self._pypubsub_publisher.subscribe(
listener=subscriber, topicName=self._pypubsub_publisher.ALL_TOPICS
)
def subscribe_type(
self, event_type: AbstractEvent, subscriber: Callable[[AbstractEvent], None]
):
# pypubsub.pub.subscribe needs a string as the topic/event name
event_type_name = event_type.__name__
pub.subscribe(listener=subscriber, topicName=event_type_name)
self._pypubsub_publisher.subscribe(listener=subscriber, topicName=event_type_name)
@staticmethod
def subscribe_tag(tag: str, subscriber: Callable[[AbstractEvent], None]):
pub.subscribe(listener=subscriber, topicName=tag)
def subscribe_tag(self, tag: str, subscriber: Callable[[AbstractEvent], None]):
self._pypubsub_publisher.subscribe(listener=subscriber, topicName=tag)
@staticmethod
def publish(event: AbstractEvent, data: Any = None):
def publish(self, event: AbstractEvent, data: Any = None):
data = data if data else {}
# publish to event type's topic
event_type_name = event.__name__
pub.sendMessage(event_type_name, **data)
self._pypubsub_publisher.sendMessage(event_type_name, **data)
# publish to tags' topics
for tag in event.tags:
pub.sendMessage(tag, **data)
self._pypubsub_publisher.sendMessage(tag, **data)