Skip to content

Instantly share code, notes, and snippets.

@vsaraph
Created April 25, 2021 20:33
Show Gist options
  • Save vsaraph/3eec85203302c7072fffa8b79eae84b1 to your computer and use it in GitHub Desktop.
Save vsaraph/3eec85203302c7072fffa8b79eae84b1 to your computer and use it in GitHub Desktop.
really really simple pub/sub in python
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