Sometimes we need publish-subscribe kind of communications between components running in the same process. It is even better if the components don't need to know each-other as that simplifies the design of complex and highly-concurrent components.
We may design similar systems using Queues also. But then also, coupling between components are not completely eliminated and we end up spawning threads and writing lots of complex logic ourselves. Moreover the pattern gets repeated across many pieces and ultimately making it a nightmare to weave the components together in a simpler way.
So, Here is a Python eventbus library, geeteventbus which is addressing exactly these problems we are facing.
The API related documentations are available here .
geeteventbus is inspired by the Java library guava eventbus. But it is not exactly the similar to Guava eventbus.
To install the library, issue the below command:
$ sudo pip install geeteventbus
This is a platform independent package and so may be used on any OS where Python can be run.
Below diagram explains the architecture of the event-bus.
There are three type of components here. The publishers post events to the event-bus. The event-bus takes care of delivering the events to appropriate subscribers. The subscribers registers themselves to the event-bus and they register themselves for certain topics. Each event is associated with a topic, data and an optional ordering field. The topic of the event decides which subscribers it will be delivered to by the event-bus.
The event-bus can be synchronous or asynchronous.
- A synchronous event-bus delivers the events from the same threads the were posted from.
- An asynchronous event-bus delivers the events to the subscribers from different threads. Basically, here the events are delivered from some of the executor threads run by the event-bus internally.
- While creating the event-bus, we may declare the future subscribers to be thread-safe. In that case, the subscribers invocation won't be synchronized.
- In some cases, we may want the events to be processed by the subscribers in the same order as they were posted. To enforce that, event objects are created with a special ordering field. E.g. event('atopic', 'somedata for this event', 'an-ordering-key'). All the events with the ordering key "an-ordering-key" will be processed in the same order they were posted to the event-bus.
- Multiple event-bus can be created in the same process if needed.