Complete the code to define the main component that receives messages from publishers.
class [1]: def __init__(self): self.subscribers = [] def subscribe(self, subscriber): self.subscribers.append(subscriber) def publish(self, message): for subscriber in self.subscribers: subscriber.receive(message)
The Broker is the central component that receives messages from publishers and forwards them to subscribers.
Complete the code to define the method that subscribers use to receive messages.
class Subscriber: def receive(self, [1]): print(f"Received: {message}")
The method parameter should be named message to match the print statement and represent the incoming data.
Fix the error in the publish method to correctly send messages to subscribers.
def publish(self, message): for subscriber in self.subscribers: subscriber.[1](message)
The receive method is called on subscribers to deliver the message.
Fill both blanks to create a dictionary that maps topics to subscriber lists.
class Broker: def __init__(self): self.topics = [1] # Initialize empty dictionary def subscribe(self, topic, subscriber): if topic not in self.topics: self.topics[topic] = [2] # Initialize list for new topic self.topics[topic].append(subscriber)
The topics attribute is a dictionary ({}), and each topic maps to a list ([]), which holds subscribers.
Fill all three blanks to implement publishing a message to all subscribers of a topic.
def publish(self, topic, message): subscribers = self.topics.get([1], [2]) for subscriber in subscribers: subscriber.[3](message)
We get the list of subscribers for the topic, defaulting to an empty list [] if none exist, then call receive on each subscriber.