Created
April 25, 2021 20:33
-
-
Save vsaraph/3eec85203302c7072fffa8b79eae84b1 to your computer and use it in GitHub Desktop.
really really simple pub/sub in python
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 Publisher: | |
def __init__(self): | |
self.subscribers = [] | |
def publish(self, message): | |
print("publishing message: {msg}".format(msg=message)) | |
for subscriber in self.subscribers: | |
subscriber.onReceive(message) | |
def addSubscriber(self, subscriber): | |
self.subscribers.append(subscriber) | |
class Subscriber: | |
def subscribeTo(self, publisher, onReceive): | |
publisher.addSubscriber(self) | |
self.onReceive = onReceive | |
p = Publisher() | |
s1 = Subscriber() | |
s2 = Subscriber() | |
s1.subscribeTo(p, lambda message: print("S1 received: {msg}".format(msg=message))) | |
s2.subscribeTo(p, lambda message: print("S2 received: {msg}".format(msg=message))) | |
p.publish("test message") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment